Model structs.
| 29 | * Model structs. |
| 30 | */ |
| 31 | class StructType extends HiveType { |
| 32 | private static final String COL_PREFIX = "_col"; |
| 33 | private static final Comparator<String> FIELD_COMPARATOR = (left, right) -> { |
| 34 | if (left == null) { |
| 35 | return right == null ? 0 : -1; |
| 36 | } else if (right == null) { |
| 37 | return 1; |
| 38 | } else if (left.startsWith(COL_PREFIX)) { |
| 39 | if (right.startsWith(COL_PREFIX)) { |
| 40 | try { |
| 41 | int leftInt = Integer.parseInt(left.substring(COL_PREFIX.length())); |
| 42 | int rightInt = Integer.parseInt(right.substring(COL_PREFIX.length())); |
| 43 | return Integer.compare(leftInt, rightInt); |
| 44 | } catch (Exception e) { |
| 45 | // fall back to the normal rules |
| 46 | } |
| 47 | } else { |
| 48 | return 1; |
| 49 | } |
| 50 | } else if (right.startsWith(COL_PREFIX)) { |
| 51 | return 1; |
| 52 | } |
| 53 | return left.compareTo(right); |
| 54 | }; |
| 55 | |
| 56 | final Map<String, HiveType> fields = new TreeMap<>(FIELD_COMPARATOR); |
| 57 | |
| 58 | StructType() { |
| 59 | super(Kind.STRUCT); |
| 60 | } |
| 61 | |
| 62 | @Override |
| 63 | public String toString() { |
| 64 | StringBuilder buf = new StringBuilder("struct<"); |
| 65 | boolean first = true; |
| 66 | for (Map.Entry<String, HiveType> field : fields.entrySet()) { |
| 67 | if (!first) { |
| 68 | buf.append(','); |
| 69 | } else { |
| 70 | first = false; |
| 71 | } |
| 72 | buf.append(field.getKey()); |
| 73 | buf.append(':'); |
| 74 | buf.append(field.getValue().toString()); |
| 75 | } |
| 76 | buf.append(">"); |
| 77 | return buf.toString(); |
| 78 | } |
| 79 | |
| 80 | public StructType addField(String name, HiveType fieldType) { |
| 81 | fields.put(name, fieldType); |
| 82 | return this; |
| 83 | } |
| 84 | |
| 85 | @Override |
| 86 | public boolean equals(Object other) { |
| 87 | return super.equals(other) && fields.equals(((StructType) other).fields); |
| 88 | } |