23
23
import com .google .cloud .bigquery .CopyJobConfiguration ;
24
24
import com .google .cloud .bigquery .Job ;
25
25
import com .google .cloud .bigquery .JobInfo ;
26
+ import com .google .cloud .bigquery .Table ;
26
27
import com .google .cloud .bigquery .TableId ;
28
+ import org .threeten .bp .Instant ;
27
29
28
30
// Sample to undeleting a table
29
31
public class UndeleteTable {
@@ -42,15 +44,25 @@ public static void undeleteTable(String datasetName, String tableName, String re
42
44
// once, and can be reused for multiple requests.
43
45
BigQuery bigquery = BigQueryOptions .getDefaultInstance ().getService ();
44
46
45
- // "Accidentally" delete the table.
46
- bigquery .delete (TableId .of (datasetName , tableName ));
47
-
48
47
// Record the current time. We'll use this as the snapshot time
49
48
// for recovering the table.
50
- long snapTime = System .currentTimeMillis ();
49
+ long snapshotEpoch = Instant .now ().toEpochMilli ();
50
+
51
+ // [START_EXCLUDE]
52
+ // Due to very short lifecycle of the table, ensure we're not picking a time
53
+ // prior to the table creation due to time drift between backend and client.
54
+ Table table = bigquery .getTable (TableId .of (datasetName , tableName ));
55
+ Long createdEpoch = table .getCreationTime ();
56
+ if (createdEpoch > snapshotEpoch ) {
57
+ snapshotEpoch = createdEpoch ;
58
+ }
59
+ // [END_EXCLUDE]
60
+
61
+ // "Accidentally" delete the table.
62
+ bigquery .delete (TableId .of (datasetName , tableName ));
51
63
52
64
// Construct the restore-from tableID using a snapshot decorator.
53
- String snapshotTableId = String .format ("%s@%d" , tableName , snapTime );
65
+ String snapshotTableId = String .format ("%s@%d" , tableName , snapshotEpoch );
54
66
55
67
// Construct and run a copy job.
56
68
CopyJobConfiguration configuration =
0 commit comments