MCPcopy Create free account
hub / github.com/cockroachdb/cockroachdb-parser / sqlStdToDuration

Function sqlStdToDuration

pkg/util/duration/parse.go:182–402  ·  view source on GitHub ↗

Parses a SQL standard interval string. See the following links for examples: - http://www.postgresql.org/docs/9.1/static/datatype-datetime.html#DATATYPE-INTERVAL-INPUT-EXAMPLES - http://www.ibm.com/support/knowledgecenter/SSGU8G_12.1.0/com.ibm.esqlc.doc/ids_esqlc_0190.htm

(s string, itm types.IntervalTypeMetadata)

Source from the content-addressed store, hash-verified

180// - http://www.postgresql.org/docs/9.1/static/datatype-datetime.html#DATATYPE-INTERVAL-INPUT-EXAMPLES
181// - http://www.ibm.com/support/knowledgecenter/SSGU8G_12.1.0/com.ibm.esqlc.doc/ids_esqlc_0190.htm
182func sqlStdToDuration(s string, itm types.IntervalTypeMetadata) (Duration, error) {
183 var d Duration
184 parts := strings.Fields(s)
185 if len(parts) > 3 || len(parts) == 0 {
186 return d, newInvalidSQLDurationError(s)
187 }
188 // Index of which part(s) have been parsed for detecting bad order such as `HH:MM:SS Year-Month`.
189 parsedIdx := nothingParsed
190 // Both 'Day' and 'Second' can be float, but 'Day Second'::interval is invalid.
191 floatParsed := false
192 // Parsing backward makes it easy to distinguish 'Day' and 'Second' when encountering a single value.
193 // `1-2 5 9:` and `1-2 5`
194 // | |
195 // day ---+ |
196 // second ---------------+
197 for i := len(parts) - 1; i >= 0; i-- {
198 // Parses leading sign
199 part := parts[i]
200
201 consumeNeg := func(str string) (newStr string, mult int64, ok bool) {
202 neg := false
203 // Consumes [-+]
204 if str != "" {
205 c := str[0]
206 if c == '-' || c == '+' {
207 neg = c == '-'
208 str = str[1:]
209 }
210 }
211 if len(str) == 0 {
212 return str, 0, false
213 }
214 if str[0] == '-' || str[0] == '+' {
215 return str, 0, false
216 }
217
218 mult = 1
219 if neg {
220 mult = -1
221 }
222 return str, mult, true
223 }
224
225 var mult int64
226 var ok bool
227 if part, mult, ok = consumeNeg(part); !ok {
228 return d, newInvalidSQLDurationError(s)
229 }
230
231 if strings.ContainsRune(part, ':') {
232 // Try to parse as HH:MM:SS
233 if parsedIdx != nothingParsed {
234 return d, newInvalidSQLDurationError(s)
235 }
236 parsedIdx = hmsParsed
237 // Colon-separated intervals in Postgres are odd. They have day, hour,
238 // minute, or second parts depending on number of fields and if the field
239 // is an int or float.

Callers 1

ParseIntervalFunction · 0.85

Calls 9

AddMethod · 0.95
SubMethod · 0.95
MakeDurationFunction · 0.85
MulFloatMethod · 0.80
IsMinuteToSecondMethod · 0.80
MulMethod · 0.80
IsDayToHourMethod · 0.80
ContainsMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…