Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python API for restoring delta table #903

Closed
Closed
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
40 changes: 40 additions & 0 deletions python/delta/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,46 @@ def upgradeTableProtocol(self, readerVersion: int, writerVersion: int) -> None:
type(writerVersion))
jdt.upgradeTableProtocol(readerVersion, writerVersion)

@since(1.2) # type: ignore[arg-type]
def restoreToVersion(self, version: int) -> DataFrame:
"""
Restore the DeltaTable to an older version of the table specified by version number.

Example::

deltaTable.restoreToVersion(1)

:param version: target version of restored table
:return: Dataframe with metrics of restore operation.
:rtype: pyspark.sql.DataFrame
"""

return DataFrame(
self._jdt.restoreToVersion(version),
self._spark._wrapped # type: ignore[attr-defined]
)

@since(1.2) # type: ignore[arg-type]
def restoreToTimestamp(self, timestamp: str) -> DataFrame:
"""
Restore the DeltaTable to an older version of the table specified by a timestamp.
Timestamp can be of the format yyyy-MM-dd or yyyy-MM-dd HH:mm:ss

Example::

deltaTable.restoreToTimestamp('2021-01-01')
deltaTable.restoreToTimestamp('2021-01-01 01:01:01')

:param timestamp: target timestamp of restored table
:return: Dataframe with metrics of restore operation.
:rtype: pyspark.sql.DataFrame
"""

return DataFrame(
self._jdt.restoreToTimestamp(timestamp),
self._spark._wrapped # type: ignore[attr-defined]
)

@staticmethod
def _dict_to_jmap(
sparkSession: SparkSession,
Expand Down
47 changes: 44 additions & 3 deletions python/delta/tests/test_deltatable.py
Original file line number Diff line number Diff line change
Expand Up @@ -791,6 +791,42 @@ def test_protocolUpgrade(self) -> None:
with self.assertRaisesRegex(ValueError, "writerVersion"):
dt.upgradeTableProtocol(1, {}) # type: ignore[arg-type]

def test_restoreToVersion(self) -> None:
self.__writeDeltaTable([('a', 1), ('b', 2)])
self.__overwriteDeltaTable([('a', 3), ('b', 2)],
schema=["key_new", "value_new"],
overwriteSchema='true')

overwritten = DeltaTable.forPath(self.spark, self.tempFile).toDF()
self.__checkAnswer(overwritten,
[Row(key_new='a', value_new=3), Row(key_new='b', value_new=2)])

DeltaTable.forPath(self.spark, self.tempFile).restoreToVersion(0)
restored = DeltaTable.forPath(self.spark, self.tempFile).toDF()

self.__checkAnswer(restored, [Row(key='a', value=1), Row(key='b', value=2)])

def test_restoreToTimestamp(self) -> None:
self.__writeDeltaTable([('a', 1), ('b', 2)])
timestampToRestore = DeltaTable.forPath(self.spark, self.tempFile) \
.history() \
.head() \
.timestamp \
.strftime('%Y-%m-%d %H:%M:%S.%f')

self.__overwriteDeltaTable([('a', 3), ('b', 2)],
schema=["key_new", "value_new"],
overwriteSchema='true')
vkorukanti marked this conversation as resolved.
Show resolved Hide resolved

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add check to verify that data has changed?
self.__checkAnswer(restored, [Row(key='a', value=3), Row(key='b', value=2)])?

Similarly in the above test

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both tests are updated

overwritten = DeltaTable.forPath(self.spark, self.tempFile).toDF()
self.__checkAnswer(overwritten,
[Row(key_new='a', value_new=3), Row(key_new='b', value_new=2)])

DeltaTable.forPath(self.spark, self.tempFile).restoreToTimestamp(timestampToRestore)

restored = DeltaTable.forPath(self.spark, self.tempFile).toDF()
self.__checkAnswer(restored, [Row(key='a', value=1), Row(key='b', value=2)])

def __checkAnswer(self, df: DataFrame,
expectedAnswer: List[Any],
schema: Union[StructType, List[str]] = ["key", "value"]) -> None:
Expand Down Expand Up @@ -818,9 +854,14 @@ def __writeAsTable(self, datalist: List[Tuple[Any, Any]], tblName: str) -> None:
df = self.spark.createDataFrame(datalist, ["key", "value"])
df.write.format("delta").saveAsTable(tblName)

def __overwriteDeltaTable(self, datalist: List[Tuple[Any, Any]]) -> None:
df = self.spark.createDataFrame(datalist, ["key", "value"])
df.write.format("delta").mode("overwrite").save(self.tempFile)
def __overwriteDeltaTable(self, datalist: List[Tuple[Any, Any]],
schema: Union[StructType, List[str]] = ["key", "value"],
overwriteSchema: str = 'false') -> None:
df = self.spark.createDataFrame(datalist, schema)
df.write.format("delta") \
.option('overwriteSchema', overwriteSchema) \
.mode("overwrite") \
.save(self.tempFile)

def __createFile(self, fileName: str, content: Any) -> None:
with open(os.path.join(self.tempFile, fileName), 'w') as f:
Expand Down