|
16 | 16 |
|
17 | 17 | import json |
18 | 18 | import types |
19 | | - |
| 19 | +import re |
| 20 | +from dataclasses import dataclass |
20 | 21 | from google.protobuf.message import Message |
21 | 22 | from google.protobuf.internal.enum_type_wrapper import EnumTypeWrapper |
22 | 23 |
|
@@ -97,6 +98,152 @@ def serialize(self): |
97 | 98 | return json.dumps(self, sort_keys=True, separators=(",", ":")) |
98 | 99 |
|
99 | 100 |
|
| 101 | +@dataclass |
| 102 | +class Interval: |
| 103 | + """Represents a Spanner INTERVAL type. |
| 104 | +
|
| 105 | + An interval is a combination of months, days and nanoseconds. |
| 106 | + Internally, Spanner supports Interval value with the following range of individual fields: |
| 107 | + months: [-120000, 120000] |
| 108 | + days: [-3660000, 3660000] |
| 109 | + nanoseconds: [-316224000000000000000, 316224000000000000000] |
| 110 | + """ |
| 111 | + |
| 112 | + months: int = 0 |
| 113 | + days: int = 0 |
| 114 | + nanos: int = 0 |
| 115 | + |
| 116 | + def __str__(self) -> str: |
| 117 | + """Returns the ISO8601 duration format string representation.""" |
| 118 | + result = ["P"] |
| 119 | + |
| 120 | + # Handle years and months |
| 121 | + if self.months: |
| 122 | + is_negative = self.months < 0 |
| 123 | + abs_months = abs(self.months) |
| 124 | + years, months = divmod(abs_months, 12) |
| 125 | + if years: |
| 126 | + result.append(f"{'-' if is_negative else ''}{years}Y") |
| 127 | + if months: |
| 128 | + result.append(f"{'-' if is_negative else ''}{months}M") |
| 129 | + |
| 130 | + # Handle days |
| 131 | + if self.days: |
| 132 | + result.append(f"{self.days}D") |
| 133 | + |
| 134 | + # Handle time components |
| 135 | + if self.nanos: |
| 136 | + result.append("T") |
| 137 | + nanos = abs(self.nanos) |
| 138 | + is_negative = self.nanos < 0 |
| 139 | + |
| 140 | + # Convert to hours, minutes, seconds |
| 141 | + nanos_per_hour = 3600000000000 |
| 142 | + hours, nanos = divmod(nanos, nanos_per_hour) |
| 143 | + if hours: |
| 144 | + if is_negative: |
| 145 | + result.append("-") |
| 146 | + result.append(f"{hours}H") |
| 147 | + |
| 148 | + nanos_per_minute = 60000000000 |
| 149 | + minutes, nanos = divmod(nanos, nanos_per_minute) |
| 150 | + if minutes: |
| 151 | + if is_negative: |
| 152 | + result.append("-") |
| 153 | + result.append(f"{minutes}M") |
| 154 | + |
| 155 | + nanos_per_second = 1000000000 |
| 156 | + seconds, nanos_fraction = divmod(nanos, nanos_per_second) |
| 157 | + |
| 158 | + if seconds or nanos_fraction: |
| 159 | + if is_negative: |
| 160 | + result.append("-") |
| 161 | + if seconds: |
| 162 | + result.append(str(seconds)) |
| 163 | + elif nanos_fraction: |
| 164 | + result.append("0") |
| 165 | + |
| 166 | + if nanos_fraction: |
| 167 | + nano_str = f"{nanos_fraction:09d}" |
| 168 | + trimmed = nano_str.rstrip("0") |
| 169 | + if len(trimmed) <= 3: |
| 170 | + while len(trimmed) < 3: |
| 171 | + trimmed += "0" |
| 172 | + elif len(trimmed) <= 6: |
| 173 | + while len(trimmed) < 6: |
| 174 | + trimmed += "0" |
| 175 | + else: |
| 176 | + while len(trimmed) < 9: |
| 177 | + trimmed += "0" |
| 178 | + result.append(f".{trimmed}") |
| 179 | + result.append("S") |
| 180 | + |
| 181 | + if len(result) == 1: |
| 182 | + result.append("0Y") # Special case for zero interval |
| 183 | + |
| 184 | + return "".join(result) |
| 185 | + |
| 186 | + @classmethod |
| 187 | + def from_str(cls, s: str) -> "Interval": |
| 188 | + """Parse an ISO8601 duration format string into an Interval.""" |
| 189 | + pattern = r"^P(-?\d+Y)?(-?\d+M)?(-?\d+D)?(T(-?\d+H)?(-?\d+M)?(-?((\d+([.,]\d{1,9})?)|([.,]\d{1,9}))S)?)?$" |
| 190 | + match = re.match(pattern, s) |
| 191 | + if not match or len(s) == 1: |
| 192 | + raise ValueError(f"Invalid interval format: {s}") |
| 193 | + |
| 194 | + parts = match.groups() |
| 195 | + if not any(parts[:3]) and not parts[3]: |
| 196 | + raise ValueError( |
| 197 | + f"Invalid interval format: at least one component (Y/M/D/H/M/S) is required: {s}" |
| 198 | + ) |
| 199 | + |
| 200 | + if parts[3] == "T" and not any(parts[4:7]): |
| 201 | + raise ValueError( |
| 202 | + f"Invalid interval format: time designator 'T' present but no time components specified: {s}" |
| 203 | + ) |
| 204 | + |
| 205 | + def parse_num(s: str, suffix: str) -> int: |
| 206 | + if not s: |
| 207 | + return 0 |
| 208 | + return int(s.rstrip(suffix)) |
| 209 | + |
| 210 | + years = parse_num(parts[0], "Y") |
| 211 | + months = parse_num(parts[1], "M") |
| 212 | + total_months = years * 12 + months |
| 213 | + |
| 214 | + days = parse_num(parts[2], "D") |
| 215 | + |
| 216 | + nanos = 0 |
| 217 | + if parts[3]: # Has time component |
| 218 | + # Convert hours to nanoseconds |
| 219 | + hours = parse_num(parts[4], "H") |
| 220 | + nanos += hours * 3600000000000 |
| 221 | + |
| 222 | + # Convert minutes to nanoseconds |
| 223 | + minutes = parse_num(parts[5], "M") |
| 224 | + nanos += minutes * 60000000000 |
| 225 | + |
| 226 | + # Handle seconds and fractional seconds |
| 227 | + if parts[6]: |
| 228 | + seconds = parts[6].rstrip("S") |
| 229 | + if "," in seconds: |
| 230 | + seconds = seconds.replace(",", ".") |
| 231 | + |
| 232 | + if "." in seconds: |
| 233 | + sec_parts = seconds.split(".") |
| 234 | + whole_seconds = sec_parts[0] if sec_parts[0] else "0" |
| 235 | + nanos += int(whole_seconds) * 1000000000 |
| 236 | + frac = sec_parts[1][:9].ljust(9, "0") |
| 237 | + frac_nanos = int(frac) |
| 238 | + if seconds.startswith("-"): |
| 239 | + frac_nanos = -frac_nanos |
| 240 | + nanos += frac_nanos |
| 241 | + else: |
| 242 | + nanos += int(seconds) * 1000000000 |
| 243 | + |
| 244 | + return cls(months=total_months, days=days, nanos=nanos) |
| 245 | + |
| 246 | + |
100 | 247 | def _proto_message(bytes_val, proto_message_object): |
101 | 248 | """Helper for :func:`get_proto_message`. |
102 | 249 | parses serialized protocol buffer bytes data into proto message. |
|
0 commit comments