1 /*
2 * PostRR - src/rrtimeslice.c
3 * Copyright (C) 2012 Sebastian 'tokkee' Harl <sh@tokkee.org>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
17 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
19 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
28 /*
29 * A PostgreSQL data-type providing a timeslice implementing round-robin
30 * features.
31 */
33 #include "postrr.h"
34 #include "utils/pg_spi.h"
36 #include <string.h>
38 #include <postgres.h>
39 #include <fmgr.h>
41 /* Postgres utilities */
42 #include <access/hash.h>
43 #include <executor/spi.h>
44 #include <utils/array.h>
45 #include <utils/datetime.h>
46 #include <utils/timestamp.h>
47 #include <miscadmin.h> /* DateStyle, IntervalStyle */
49 #ifdef HAVE_INT64_TIMESTAMP
50 # define TSTAMP_TO_INT64(t) (t)
51 # define INT64_TO_TSTAMP(i) (i)
52 #else /* ! HAVE_INT64_TIMESTAMP */
53 # define TSTAMP_TO_INT64(t) (int64)((t) * (double)USECS_PER_SEC)
54 # define INT64_TO_TSTAMP(i) ((double)(i) / (double)USECS_PER_SEC)
55 #endif
57 /*
58 * data type
59 */
61 struct rrtimeslice {
62 Timestamp tstamp;
63 int32 tsid;
64 uint32 seq;
65 };
67 /*
68 * internal helper functions
69 */
71 static int32
72 rrtimeslice_set_spec(int32 len, int32 num)
73 {
74 int spi_rc;
76 char query[256];
77 int32 typmod = 0;
79 if ((len <= 0) || (num <= 0))
80 ereport(ERROR, (
81 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
82 errmsg("rrtimeslice(%i, %i) "
83 "length/num may not be less than zero",
84 len, num)
85 ));
87 if ((spi_rc = SPI_connect()) != SPI_OK_CONNECT)
88 ereport(ERROR, (
89 errmsg("failed to store rrtimeslice spec: "
90 "could not connect to SPI manager: %s",
91 SPI_result_code_string(spi_rc))
92 ));
94 snprintf(query, sizeof(query),
95 "SELECT tsid FROM postrr.rrtimeslices "
96 "WHERE tslen = %d AND tsnum = %d "
97 "LIMIT 1", len, num);
98 query[sizeof(query) - 1] = '\0';
100 spi_rc = pg_spi_get_int(query, 1, &typmod);
101 if (spi_rc == PG_SPI_OK) {
102 SPI_finish();
103 return typmod;
104 }
105 else if (spi_rc != PG_SPI_ERROR_NO_VALUES)
106 pg_spi_ereport(ERROR, "store rrtimeslice spec", spi_rc);
108 snprintf(query, sizeof(query),
109 "SELECT nextval('postrr.tsid'::regclass)");
110 query[sizeof(query) - 1] = '\0';
112 spi_rc = pg_spi_get_int(query, 1, &typmod);
113 if ((spi_rc != PG_SPI_OK) || (typmod <= 0))
114 pg_spi_ereport(ERROR, "retrieve nextval(postrr.tsid)", spi_rc);
116 snprintf(query, sizeof(query),
117 "INSERT INTO postrr.rrtimeslices(tsid, tslen, tsnum) "
118 "VALUES (%d, %d, %d)", typmod, len, num);
119 query[sizeof(query) - 1] = '\0';
121 spi_rc = SPI_exec(query, /* max num rows = */ 1);
122 if (spi_rc != SPI_OK_INSERT)
123 ereport(ERROR, (
124 errmsg("failed to store rrtimeslice spec: "
125 "failed to execute query: %s",
126 SPI_result_code_string(spi_rc))
127 ));
129 SPI_finish();
130 return typmod;
131 } /* rrtimeslice_set_spec */
133 static int
134 rrtimeslice_get_spec(int32 typmod, int32 *len, int32 *num)
135 {
136 int spi_rc;
138 char query[256];
140 if (typmod <= 0)
141 return -1;
143 if ((spi_rc = SPI_connect()) != SPI_OK_CONNECT)
144 ereport(ERROR, (
145 errmsg("failed to determine rrtimeslice spec: "
146 "could not connect to SPI manager: %s",
147 SPI_result_code_string(spi_rc))
148 ));
150 snprintf(query, sizeof(query),
151 "SELECT tslen, tsnum FROM postrr.rrtimeslices "
152 "WHERE tsid = %d", typmod);
153 query[sizeof(query) - 1] = '\0';
155 spi_rc = pg_spi_get_int(query, 2, len, num);
156 if (spi_rc != PG_SPI_OK)
157 pg_spi_ereport(ERROR, "determine rrtimeslice spec", spi_rc);
159 SPI_finish();
160 return 0;
161 } /* rrtimeslice_get_spec */
163 static int
164 rrtimeslice_apply_typmod(rrtimeslice_t *tslice, int32 typmod)
165 {
166 int64 tstamp;
167 int64 length;
168 int64 seq;
170 int32 len = 0;
171 int32 num = 0;
173 if (rrtimeslice_get_spec(typmod, &len, &num))
174 return -1;
176 if ((len <= 0) || (num <= 0))
177 ereport(ERROR, (
178 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
179 errmsg("rrtimeslice(%i, %i) "
180 "length/num may not be less than zero",
181 len, num)
182 ));
184 tstamp = TSTAMP_TO_INT64(tslice->tstamp);
186 length = len * USECS_PER_SEC;
187 if (tstamp % length != 0)
188 tstamp = tstamp - (tstamp % length) + length;
189 seq = tstamp % (length * num) / length;
190 seq = seq % num;
192 tslice->tstamp = INT64_TO_TSTAMP(tstamp);
193 tslice->tsid = typmod;
194 tslice->seq = (uint32)seq;
195 return 0;
196 } /* rrtimeslice_apply_typmod */
198 /*
199 * prototypes for PostgreSQL functions
200 */
202 PG_FUNCTION_INFO_V1(rrtimeslice_validate);
204 PG_FUNCTION_INFO_V1(rrtimeslice_in);
205 PG_FUNCTION_INFO_V1(rrtimeslice_out);
206 PG_FUNCTION_INFO_V1(rrtimeslice_typmodin);
207 PG_FUNCTION_INFO_V1(rrtimeslice_typmodout);
209 PG_FUNCTION_INFO_V1(rrtimeslice_to_rrtimeslice);
210 PG_FUNCTION_INFO_V1(rrtimeslice_to_timestamp);
212 PG_FUNCTION_INFO_V1(rrtimeslice_seq_eq);
213 PG_FUNCTION_INFO_V1(rrtimeslice_seq_ne);
214 PG_FUNCTION_INFO_V1(rrtimeslice_seq_lt);
215 PG_FUNCTION_INFO_V1(rrtimeslice_seq_gt);
216 PG_FUNCTION_INFO_V1(rrtimeslice_seq_le);
217 PG_FUNCTION_INFO_V1(rrtimeslice_seq_ge);
218 PG_FUNCTION_INFO_V1(rrtimeslice_seq_cmp);
219 PG_FUNCTION_INFO_V1(rrtimeslice_seq_hash);
221 /*
222 * public API
223 */
225 Datum
226 rrtimeslice_validate(PG_FUNCTION_ARGS)
227 {
228 char type_info[1024];
229 char *result;
230 size_t req_len;
231 size_t len;
233 if (PG_NARGS() != 1)
234 ereport(ERROR, (
235 errmsg("rrtimeslice_validate() expect one argument"),
236 errhint("Usage rrtimeslice_validate(expected_size)")
237 ));
239 req_len = (size_t)PG_GETARG_UINT32(0);
240 len = sizeof(rrtimeslice_t);
242 if (req_len != len)
243 ereport(ERROR, (
244 errmsg("length of the rrtimeslice type "
245 "does not match the expected length"),
246 errhint("Please report a bug against PostRR")
247 ));
249 snprintf(type_info, sizeof(type_info),
250 "rrtimeslice validated successfully; type length = %zu", len);
251 type_info[sizeof(type_info) - 1] = '\0';
253 result = pstrdup(type_info);
254 PG_RETURN_CSTRING(result);
255 } /* rrtimeslice_validate */
257 Datum
258 rrtimeslice_in(PG_FUNCTION_ARGS)
259 {
260 rrtimeslice_t *tslice;
262 Timestamp tstamp = 0;
263 int32 typmod;
265 struct pg_tm tm;
266 fsec_t fsec = 0;
267 int tz = 0;
269 char *time_str;
270 int pg_dt_err;
271 char buf[MAXDATELEN + MAXDATEFIELDS];
272 char *field[MAXDATEFIELDS];
273 int ftype[MAXDATEFIELDS];
274 int num_fields = 0;
275 int dtype = 0;
277 if (PG_NARGS() != 3)
278 ereport(ERROR, (
279 errmsg("rrtimeslice_in() expects three arguments"),
280 errhint("Usage: rrtimeslice_in(col_name, oid, typmod)")
281 ));
283 tslice = (rrtimeslice_t *)palloc0(sizeof(*tslice));
284 time_str = PG_GETARG_CSTRING(0);
285 typmod = PG_GETARG_INT32(2);
287 pg_dt_err = ParseDateTime(time_str, buf, sizeof(buf),
288 field, ftype, MAXDATEFIELDS, &num_fields);
290 if (! pg_dt_err)
291 pg_dt_err = DecodeDateTime(field, ftype, num_fields,
292 &dtype, &tm, &fsec, &tz);
293 if (pg_dt_err)
294 DateTimeParseError(pg_dt_err, time_str, "rrtimeslice");
296 switch (dtype) {
297 case DTK_DATE:
298 if (tm2timestamp(&tm, fsec, NULL, &tstamp))
299 ereport(ERROR, (
300 errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
301 errmsg("timestamp out of range: %s", time_str)
302 ));
303 break;
305 case DTK_EPOCH:
306 tstamp = SetEpochTimestamp();
307 break;
309 default:
310 ereport(ERROR, (
311 errmsg("unexpected dtype %d while "
312 "parsing rrtimeslice: %s", dtype, time_str)
313 ));
314 }
316 tslice->tstamp = tstamp;
318 /* most likely, this won't happen … coerce_type
319 * (src/backend/parser/parse_coerce.c) does not pass that information to
320 * the input function but rather lets a length conversion cast do that
321 * work */
322 if (typmod > 0)
323 rrtimeslice_apply_typmod(tslice, typmod);
325 PG_RETURN_RRTIMESLICE_P(tslice);
326 } /* rrtimeslice_in */
328 Datum
329 rrtimeslice_out(PG_FUNCTION_ARGS)
330 {
331 rrtimeslice_t *tslice;
333 Interval interval;
335 struct pg_tm tm;
336 fsec_t fsec = 0;
337 char *tz = NULL;
339 char ts_str[MAXDATELEN + 1];
340 char buf_ts[MAXDATELEN + 1];
341 char buf_l[MAXDATELEN + 1];
342 char *result;
344 int32 len = 0;
345 int32 num = 0;
347 if (PG_NARGS() != 1)
348 ereport(ERROR, (
349 errmsg("rrtimeslice_out() expects one argument"),
350 errhint("Usage: rrtimeslice_out(rrtimeslice)")
351 ));
353 tslice = PG_GETARG_RRTIMESLICE_P(0);
355 if (TIMESTAMP_NOT_FINITE(tslice->tstamp)
356 || (timestamp2tm(tslice->tstamp, NULL, &tm, &fsec, NULL, NULL) != 0))
357 ereport(ERROR, (
358 errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
359 errmsg("invalid (non-finite) timestamp")
360 ));
361 else
362 EncodeDateTime(&tm, fsec, NULL, &tz, DateStyle, buf_ts);
364 if (! rrtimeslice_get_spec(tslice->tsid, &len, &num)) {
365 memset(&interval, 0, sizeof(interval));
366 interval.time = len * USECS_PER_SEC;
367 fsec = 0;
369 if (interval2tm(interval, &tm, &fsec))
370 ereport(ERROR, (
371 errmsg("could not convert interval to tm")
372 ));
373 }
374 else {
375 strncpy(buf_l, "ERR", sizeof(buf_l));
376 buf_l[sizeof(buf_l) - 1] = '\0';
377 }
379 EncodeInterval(&tm, fsec, IntervalStyle, buf_l);
381 snprintf(ts_str, sizeof(ts_str), "%s -%s (#%i)",
382 buf_ts, buf_l, tslice->seq);
384 result = pstrdup(ts_str);
385 PG_RETURN_CSTRING(result);
386 } /* rrtimeslice_out */
388 Datum
389 rrtimeslice_typmodin(PG_FUNCTION_ARGS)
390 {
391 ArrayType *tm_array;
393 int32 *spec;
394 int spec_elems = 0;
395 int32 typmod;
397 if (PG_NARGS() != 1)
398 ereport(ERROR, (
399 errmsg("rrtimeslice_typmodin() expects one argument"),
400 errhint("Usage: rrtimeslice_typmodin(array)")
401 ));
403 tm_array = PG_GETARG_ARRAYTYPE_P(0);
405 spec = ArrayGetIntegerTypmods(tm_array, &spec_elems);
406 if (spec_elems != 2)
407 ereport(ERROR, (
408 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
409 errmsg("invalid rrtimeslice type modifier"),
410 errhint("Usage: rrtimeslice(<slice_len>, <num>)")
411 ));
413 typmod = rrtimeslice_set_spec(spec[0], spec[1]);
414 PG_RETURN_INT32(typmod);
415 } /* rrtimeslice_typmodin */
417 Datum
418 rrtimeslice_typmodout(PG_FUNCTION_ARGS)
419 {
420 int32 typmod;
421 char tm_str[1024];
422 char *result;
424 int32 len = 0;
425 int32 num = 0;
427 if (PG_NARGS() != 1)
428 ereport(ERROR, (
429 errmsg("rrtimeslice_typmodout() expects one argument"),
430 errhint("Usage: rrtimeslice_typmodout(typmod)")
431 ));
433 typmod = PG_GETARG_INT32(0);
434 if (rrtimeslice_get_spec(typmod, &len, &num))
435 tm_str[0] = '\0';
436 else if ((len <= 0) || (num <= 0))
437 snprintf(tm_str, sizeof(tm_str), "(#ERR, #ERR)");
438 else
439 snprintf(tm_str, sizeof(tm_str), "(%d, %d)", len, num);
441 result = pstrdup(tm_str);
442 PG_RETURN_CSTRING(result);
443 } /* rrtimeslice_typmodout */
445 Datum
446 rrtimeslice_to_rrtimeslice(PG_FUNCTION_ARGS)
447 {
448 rrtimeslice_t *tslice;
449 int32 typmod;
451 if (PG_NARGS() != 3)
452 ereport(ERROR, (
453 errmsg("rrtimeslice_to_rrtimeslice() "
454 "expects three arguments"),
455 errhint("Usage: rrtimeslice_to_rrtimeslice"
456 "(rrtimeslice, typmod, is_explicit)")
457 ));
459 tslice = PG_GETARG_RRTIMESLICE_P(0);
460 typmod = PG_GETARG_INT32(1);
462 if (typmod > 0) {
463 if ((! tslice->tsid) && (! tslice->seq))
464 rrtimeslice_apply_typmod(tslice, typmod);
465 else
466 ereport(ERROR, (
467 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
468 errmsg("invalid cast: cannot cast rrtimeslices "
469 "with different typmod (yet)")
470 ));
471 }
473 PG_RETURN_RRTIMESLICE_P(tslice);
474 } /* rrtimeslice_to_rrtimeslice */
476 Datum
477 rrtimeslice_to_timestamp(PG_FUNCTION_ARGS)
478 {
479 rrtimeslice_t *tslice;
481 if (PG_NARGS() != 1)
482 ereport(ERROR, (
483 errmsg("rrtimeslice_to_timestamp() "
484 "expects one argument"),
485 errhint("Usage: rrtimeslice_to_timestamp"
486 "(rrtimeslice)")
487 ));
489 tslice = PG_GETARG_RRTIMESLICE_P(0);
490 PG_RETURN_TIMESTAMP(tslice->tstamp);
491 } /* rrtimeslice_to_timestamp */
493 int
494 rrtimeslice_seq_cmp_internal(rrtimeslice_t *ts1, rrtimeslice_t *ts2)
495 {
496 if ((! ts1) && (! ts2))
497 return 0;
498 else if (! ts1)
499 return -1;
500 else if (! ts2)
501 return 1;
503 if (ts1->tsid && (! ts2->tsid))
504 rrtimeslice_apply_typmod(ts2, ts1->tsid);
505 else if ((! ts1->tsid) && ts2->tsid)
506 rrtimeslice_apply_typmod(ts1, ts2->tsid);
508 if (ts1->tsid != ts2->tsid) /* XXX: compare len/num */
509 ereport(ERROR, (
510 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
511 errmsg("invalid comparison: cannot compare "
512 "rrtimeslices with different typmods (yet)")
513 ));
515 if (ts1->seq < ts2->seq)
516 return -1;
517 else if (ts1->seq == ts2->seq)
518 return 0;
519 else
520 return 1;
521 } /* rrtimeslice_seq_cmp_internal */
523 Datum
524 rrtimeslice_seq_eq(PG_FUNCTION_ARGS)
525 {
526 rrtimeslice_t *ts1 = PG_GETARG_RRTIMESLICE_P(0);
527 rrtimeslice_t *ts2 = PG_GETARG_RRTIMESLICE_P(1);
529 PG_RETURN_BOOL(rrtimeslice_seq_cmp_internal(ts1, ts2) == 0);
530 } /* rrtimeslice_seq_eq */
532 Datum
533 rrtimeslice_seq_ne(PG_FUNCTION_ARGS)
534 {
535 rrtimeslice_t *ts1 = PG_GETARG_RRTIMESLICE_P(0);
536 rrtimeslice_t *ts2 = PG_GETARG_RRTIMESLICE_P(1);
538 PG_RETURN_BOOL(rrtimeslice_seq_cmp_internal(ts1, ts2) != 0);
539 } /* rrtimeslice_seq_ne */
541 Datum
542 rrtimeslice_seq_lt(PG_FUNCTION_ARGS)
543 {
544 rrtimeslice_t *ts1 = PG_GETARG_RRTIMESLICE_P(0);
545 rrtimeslice_t *ts2 = PG_GETARG_RRTIMESLICE_P(1);
547 PG_RETURN_BOOL(rrtimeslice_seq_cmp_internal(ts1, ts2) < 0);
548 } /* rrtimeslice_seq_lt */
550 Datum
551 rrtimeslice_seq_le(PG_FUNCTION_ARGS)
552 {
553 rrtimeslice_t *ts1 = PG_GETARG_RRTIMESLICE_P(0);
554 rrtimeslice_t *ts2 = PG_GETARG_RRTIMESLICE_P(1);
556 PG_RETURN_BOOL(rrtimeslice_seq_cmp_internal(ts1, ts2) <= 0);
557 } /* rrtimeslice_seq_le */
559 Datum
560 rrtimeslice_seq_gt(PG_FUNCTION_ARGS)
561 {
562 rrtimeslice_t *ts1 = PG_GETARG_RRTIMESLICE_P(0);
563 rrtimeslice_t *ts2 = PG_GETARG_RRTIMESLICE_P(1);
565 PG_RETURN_BOOL(rrtimeslice_seq_cmp_internal(ts1, ts2) > 0);
566 } /* rrtimeslice_seq_gt */
568 Datum
569 rrtimeslice_seq_ge(PG_FUNCTION_ARGS)
570 {
571 rrtimeslice_t *ts1 = PG_GETARG_RRTIMESLICE_P(0);
572 rrtimeslice_t *ts2 = PG_GETARG_RRTIMESLICE_P(1);
574 PG_RETURN_BOOL(rrtimeslice_seq_cmp_internal(ts1, ts2) >= 0);
575 } /* rrtimeslice_seq_ge */
577 Datum
578 rrtimeslice_seq_cmp(PG_FUNCTION_ARGS)
579 {
580 rrtimeslice_t *ts1 = PG_GETARG_RRTIMESLICE_P(0);
581 rrtimeslice_t *ts2 = PG_GETARG_RRTIMESLICE_P(1);
583 PG_RETURN_INT32(rrtimeslice_seq_cmp_internal(ts1, ts2));
584 } /* rrtimeslice_seq_ge */
586 Datum
587 rrtimeslice_seq_hash(PG_FUNCTION_ARGS)
588 {
589 rrtimeslice_t *ts = PG_GETARG_RRTIMESLICE_P(0);
590 return hash_uint32(ts->seq);
591 } /* rrtimeslice_seq_hash */
593 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */