|
1 | 1 | package io.cloudquery.schema; |
2 | 2 |
|
| 3 | +import com.google.common.base.Objects; |
3 | 4 | import com.google.protobuf.ByteString; |
4 | 5 | import io.cloudquery.helper.ArrowHelper; |
5 | 6 | import io.cloudquery.scalar.Scalar; |
6 | 7 | import io.cloudquery.scalar.ValidationException; |
7 | 8 | import java.io.IOException; |
| 9 | +import java.nio.ByteBuffer; |
| 10 | +import java.nio.charset.StandardCharsets; |
| 11 | +import java.security.MessageDigest; |
| 12 | +import java.security.NoSuchAlgorithmException; |
8 | 13 | import java.util.ArrayList; |
| 14 | +import java.util.Collections; |
9 | 15 | import java.util.List; |
| 16 | +import java.util.UUID; |
10 | 17 | import lombok.Builder; |
11 | 18 | import lombok.Getter; |
12 | 19 | import lombok.NonNull; |
@@ -44,4 +51,44 @@ public Scalar<?> get(String columnName) { |
44 | 51 | public ByteString encode() throws IOException { |
45 | 52 | return ArrowHelper.encode(this); |
46 | 53 | } |
| 54 | + |
| 55 | + public void setCqId(UUID value) throws ValidationException { |
| 56 | + int index = table.indexOfColumn(Column.CQ_ID_COLUMN.getName()); |
| 57 | + if (index == -1) { |
| 58 | + return; |
| 59 | + } |
| 60 | + this.data.get(index).set(value); |
| 61 | + } |
| 62 | + |
| 63 | + public void resolveCQId(boolean deterministicCqId) |
| 64 | + throws ValidationException, NoSuchAlgorithmException { |
| 65 | + UUID randomUUID = UUID.randomUUID(); |
| 66 | + if (!deterministicCqId) { |
| 67 | + this.setCqId(randomUUID); |
| 68 | + return; |
| 69 | + } |
| 70 | + |
| 71 | + // Use an array list to support sorting |
| 72 | + ArrayList<String> pks = new ArrayList<>(this.table.primaryKeys()); |
| 73 | + boolean cqOnlyPK = |
| 74 | + pks.stream().allMatch((pk) -> Objects.equal(pk, Column.CQ_ID_COLUMN.getName())); |
| 75 | + if (cqOnlyPK) { |
| 76 | + this.setCqId(randomUUID); |
| 77 | + return; |
| 78 | + } |
| 79 | + |
| 80 | + Collections.sort(pks); |
| 81 | + // Generate uuid v5 (same as sha-1) |
| 82 | + MessageDigest digest = MessageDigest.getInstance("SHA-1"); |
| 83 | + for (String pk : pks) { |
| 84 | + digest.update(pk.getBytes(StandardCharsets.UTF_8)); |
| 85 | + digest.update(this.get(pk).toString().getBytes(StandardCharsets.UTF_8)); |
| 86 | + } |
| 87 | + |
| 88 | + ByteBuffer byteBuffer = ByteBuffer.wrap(digest.digest()); |
| 89 | + long mostSig = byteBuffer.getLong(); |
| 90 | + long leastSig = byteBuffer.getLong(); |
| 91 | + this.setCqId(new UUID(mostSig, leastSig)); |
| 92 | + return; |
| 93 | + } |
47 | 94 | } |
0 commit comments