|
| 1 | +package org.avni_integration_service.lahi.service; |
| 2 | + |
| 3 | +import com.google.cloud.bigquery.*; |
| 4 | +import org.avni_integration_service.lahi.config.BigQueryConnector; |
| 5 | +import org.springframework.stereotype.Service; |
| 6 | + |
| 7 | +import java.util.UUID; |
| 8 | + |
| 9 | +@Service |
| 10 | +public class DataExtractorService { |
| 11 | + |
| 12 | + private final BigQueryConnector bigQueryConnector; |
| 13 | + |
| 14 | + public DataExtractorService( BigQueryConnector bigQueryConnector) { |
| 15 | + this.bigQueryConnector = bigQueryConnector; |
| 16 | + } |
| 17 | + |
| 18 | + public void queryToBigQuery(String sqlQuery) throws InterruptedException { |
| 19 | + |
| 20 | + QueryJobConfiguration queryConfig = |
| 21 | + QueryJobConfiguration.newBuilder( |
| 22 | + sqlQuery) |
| 23 | + .setUseLegacySql(false) |
| 24 | + .build(); |
| 25 | + |
| 26 | + // Create a job ID so that we can safely retry. |
| 27 | + JobId jobId = JobId.of(UUID.randomUUID().toString()); |
| 28 | + Job queryJob = bigQueryConnector.getBigQuery().create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build()); |
| 29 | + |
| 30 | + // Wait for the query to complete. |
| 31 | + queryJob = queryJob.waitFor(); |
| 32 | + |
| 33 | + // Check for errors |
| 34 | + if (queryJob == null) { |
| 35 | + throw new RuntimeException("Job no longer exists"); |
| 36 | + } else if (queryJob.getStatus().getError() != null) { |
| 37 | + // You can also look at queryJob.getStatus().getExecutionErrors() for all |
| 38 | + // errors, not just the latest one. |
| 39 | + throw new RuntimeException(queryJob.getStatus().getError().toString()); |
| 40 | + } |
| 41 | + |
| 42 | + // Get the results. |
| 43 | + TableResult result = queryJob.getQueryResults(); |
| 44 | + |
| 45 | + // TODO return result set |
| 46 | + // Print all pages of the results. |
| 47 | + for (FieldValueList row : result.iterateAll()) { |
| 48 | + // String type |
| 49 | + String name = row.get("name").getStringValue(); |
| 50 | + String age = row.get("age").getNumericValue().toPlainString(); |
| 51 | + System.out.printf("%s is of the age %s \n", name, age); |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments