Debian Codegraph @

gavo/resources/src/boosterskel.c

raw
1 /* A skeleton for an ingestion booster.
2 */
3
4
5 #define HAVE_INT64_TIMESTAMP // read this from <pg-config --includes>/c.h ?
6
7 #define _XOPEN_SOURCE
8 #define _ISOC99_SOURCE
9
10 #include <stdio.h>
11 #include <string.h>
12 #include <stdarg.h>
13 #include <ctype.h>
14 #include <inttypes.h>
15 #include <assert.h>
16 #include <math.h>
17 #include <time.h>
18 #include <endian.h>
19 #include <stdlib.h>
20 #include <errno.h>
21 #include <arpa/inet.h>
22 #include "boosterskel.h"
23
24 /* The following items should probably be collected in a parseContext */
25 char *context=NULL; // handleInvalidRecord() looks here to give
26 // more informative error messages
27 jmp_buf ignoreRecord; // longjmp target for non-letal bad records
28
29
30 /* Epoch of pq dumps. Let's hope they don't change that frequently */
31 static struct tm pqEpochParts = {
32 .tm_sec = 0,
33 .tm_min = 0,
34 .tm_hour = 0,
35 .tm_mday = 1,
36 .tm_mon = 0,
37 .tm_year = 100,
38 .tm_wday = -1,
39 .tm_yday = -1,
40 .tm_isdst = 0,
41 };
42 static time_t PqEpoch;
43
44 void die(char *format, ...)
45 {
46 va_list ap;
47 va_start(ap, format);
48 (void)fprintf(stderr, "importbooster: ");
49 (void)vfprintf(stderr, format, ap);
50 va_end(ap);
51 (void)fprintf(stderr, "\n");
52 exit(1);
53 }
54
55 void handleBadRecord(char *format, ...)
56 {
57 va_list ap;
58 va_start(ap, format);
59 (void)fprintf(stderr, "importbooster: ");
60 if (context) {
61 (void)fprintf(stderr, "Bad Record: '%s'\n", context);
62 }
63 #ifndef IGNORE_BAD_RECORDS
64 (void)vfprintf(stderr, format, ap);
65 (void)fprintf(stderr, "\n");
66 va_end(ap);
67 #else
68 va_end(ap);
69 longjmp(ignoreRecord, 1);
70 #endif
71 }
72
73 /* Use this to write to the dump */
74 #define DATA_OUT(data, nbytes, destination) \
75 fwrite(data, 1, nbytes, (FILE*)destination)
76
77 /* Use this to write into a buffer; bufp will be updated to point to
78 the next writable char. */
79 #define ADD_DATA(data, nbytes, bufp) {\
80 unsigned char *sp=(unsigned char*) data;\
81 while (sp-(unsigned char*)data<nbytes) \
82 *bufp++ = *sp++;}
83
84
85
86 void
87 j2date(int jd, int *year, int *month, int *day)
88 { /* jd -> ymd, lifted from postgresql source */
89 unsigned int julian;
90 unsigned int quad;
91 unsigned int extra;
92 int y;
93
94 julian = jd;
95 julian += 32044;
96 quad = julian / 146097;
97 extra = (julian - quad * 146097) * 4 + 3;
98 julian += 60 + quad * 3 + extra / 146097;
99 quad = julian / 1461;
100 julian -= quad * 1461;
101 y = julian * 4 / 1461;
102 julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
103 + 123;
104 y += quad * 4;
105 *year = y - 4800;
106 quad = julian * 2141 / 65536;
107 *day = julian - 7834 * quad / 256;
108 *month = (quad + 10) % 12 + 1;
109 return;
110 } /* j2date() */
111
112
113 int julian2unixtime(double julian, time_t *result)
114 {
115 struct tm datetime;
116 double hrs, mins;
117
118 julian += 0.5;
119 j2date((int)trunc(julian), &datetime.tm_year, &datetime.tm_mon,
120 &datetime.tm_mday);
121 datetime.tm_year -= 1900; /* mktime wants it like this. yuck. */
122 datetime.tm_mon -= 1;
123 hrs = (julian-trunc(julian))*24;
124 datetime.tm_hour = (int)trunc(hrs);
125 mins = (hrs-datetime.tm_hour)*60;
126 datetime.tm_min = (int)trunc(mins);
127 datetime.tm_sec = (int)trunc((mins-datetime.tm_min)*60);
128 datetime.tm_isdst = 0;
129 *result = mktime(&datetime);
130 return 0;
131 }
132
133
134 void makeTimeFromJd(Field *field)
135 { /* double field to date field */
136 assert(field->type==VAL_DOUBLE);
137 field->type = VAL_DATETIME;
138 julian2unixtime(field->val.c_double, &(field->val.time));
139 }
140
141
142 double mjdToJYear(double mjd)
143 {
144 return (mjd-51544.5)/365.25+2000;
145 }
146
147
148 void linearTransform(Field *field, double offset, double factor)
149 {
150 switch (field->type) {
151 case VAL_FLOAT:
152 field->val.c_float = offset+field->val.c_float*factor;
153 break;
154 case VAL_DOUBLE:
155 field->val.c_double = offset+field->val.c_double*factor;
156 break;
157 case VAL_INT:
158 field->val.c_int32 = offset+field->val.c_int32*factor;
159 break;
160 default:
161 /* should we raise error for other Non-NULL types? */
162 break;
163 }
164 }
165
166 void stripWhitespace(char *str)
167 {
168 char *cp=str, *dp;
169
170 while (*cp && isspace(*cp)) {
171 cp++;
172 }
173 if (!*cp) {
174 *str = 0;
175 return;
176 }
177 for (dp=str; *cp;) {
178 *dp++ = *cp++;
179 }
180 *dp-- = 0;
181 while (isspace(*dp)) {
182 *dp-- = 0;
183 }
184 }
185
186 char* copyString(char *src, char *dest, int start, int len)
187 {
188 strncpy(dest, src+start, len);
189 dest[len] = 0;
190 stripWhitespace(dest);
191 if (!*dest) {
192 return NULL;
193 }
194 return dest;
195 }
196
197
198 int isWhitespaceOnly(char *str)
199 {
200 while (*str) {
201 if (! isspace(*str++)) {
202 return 0;
203 }
204 }
205 return 1;
206 }
207
208
209 #define scanfWithWhitespace(input, format, field, expType) \
210 if (1!=sscanf(input, format, (expType*)&(field->val))) { \
211 if (!isWhitespaceOnly(input)) { \
212 handleBadRecord("Invalid literal for %s: '%s'", STRINGIFY(expType), input); \
213 } else { \
214 field->type = VAL_NULL; \
215 } \
216 }
217
218
219 void _parseWithMagicNULL(char *sscanfFormat, valType destType, char *src,
220 Field *field, int start, int len, char *magicVal)
221 {
222 char input[len+1];
223
224 copyString(src, input, start, len);
225 if (!strcmp(input, magicVal)) {
226 field->type = VAL_NULL;
227 return;
228 }
229 field->type = destType;
230 scanfWithWhitespace(input, sscanfFormat, field, float);
231 }
232
233
234 void parseFloatWithMagicNULL(char *src, Field *field, int start, int len,
235 char *magicVal)
236 {
237 _parseWithMagicNULL("%f", VAL_FLOAT, src, field, start, len, magicVal);
238 }
239
240
241 void parseDoubleWithMagicNULL(char *src, Field *field, int start, int len,
242 char *magicVal)
243 {
244 _parseWithMagicNULL("%lf", VAL_DOUBLE, src, field, start, len, magicVal);
245 }
246
247
248 void parseFloat(char *src, Field *field, int start, int len)
249 {
250 char input[len+1];
251
252 copyString(src, input, start, len);
253 field->type = VAL_FLOAT;
254 scanfWithWhitespace(input, "%f", field, float);
255 }
256
257 void parseDouble(char *src, Field *field, int start, int len)
258 {
259 char input[len+1];
260
261 copyString(src, input, start, len);
262 field->type = VAL_DOUBLE;
263 scanfWithWhitespace(input, "%lf", field, double);
264 }
265
266 void parseBigint(char *src, Field *field, int start, int len)
267 {
268 char input[len+1];
269 copyString(src, input, start, len);
270 field->type = VAL_BIGINT;
271 scanfWithWhitespace(input, "%" SCNd64, field, int64_t);
272 }
273
274 void parseInt(char *src, Field *field, int start, int len)
275 {
276 char input[len+1];
277
278 copyString(src, input, start, len);
279 field->type = VAL_INT;
280 scanfWithWhitespace(input, "%d", field, int);
281 }
282
283 void parseShort(char *src, Field *field, int start, int len)
284 {
285 char input[len+1];
286
287 copyString(src, input, start, len);
288 field->type = VAL_SHORT;
289 scanfWithWhitespace(input, "%hd", field, short);
290 }
291
292
293 void parseBlankBoolean(char *src, Field *field, int srcInd)
294 {
295 field->type = VAL_BOOL;
296
297 if (isspace(src[srcInd])) {
298 field->val.c_int8 = 0;
299 } else {
300 field->val.c_int8 = 1;
301 }
302 }
303
304 void parseString(char *src, Field *field, int start, int len, char *space)
305 {
306 copyString(src, space, start, len);
307 field->length = len;
308 field->type = VAL_TEXT;
309 field->val.c_ptr = space;
310 }
311
312 void parseStringWithMagicNULL(char *src, Field *field, int start,
313 int len, char *space, char *magic)
314 {
315 parseString(src, field, start, len, space);
316 if (!strcmp(space, magic)) {
317 field->type = VAL_NULL;
318 }
319 }
320
321 void parseChar(char *src, Field *field, int srcInd)
322 {
323 field->type = VAL_CHAR;
324 if (isspace(src[srcInd])) {
325 field->type = VAL_NULL;
326 } else {
327 field->val.c_int8 = src[srcInd];
328 }
329 }
330
331 int sscanfWithNULL(char *source, char *format, Field *field, void *dest) {
332 if (*source==0) { /* empty string, make thing NULL */
333 field->type = VAL_NULL;
334 return 1;
335 }
336 return sscanf(source, format, dest);
337 }
338
339 void real_fieldscanf(char *str, Field *f, valType type, char *fieldName, ...)
340 {
341 int itemsMatched=1;
342 va_list ap;
343
344 #ifdef AUTO_NULL
345 if (!strcmp(str, STRINGIFY_VAL(AUTO_NULL))) {
346 f->type = VAL_NULL;
347 return;
348 }
349 #endif
350 va_start(ap, fieldName);
351 f->type = type;
352 switch (type) {
353 case VAL_NULL:
354 break;
355 case VAL_BOOL:
356 handleBadRecord("Can't fieldscanf bools at %s", fieldName);
357 break;
358 case VAL_CHAR:
359 f->val.c_int8 = *str;
360 break;
361 case VAL_SHORT:
362 itemsMatched = sscanfWithNULL(str, "%hd", f, &(f->val.c_int16));
363 break;
364 case VAL_INT:
365 itemsMatched = sscanfWithNULL(str, "%d", f, &(f->val.c_int32));
366 break;
367 case VAL_FLOAT:
368 itemsMatched = sscanfWithNULL(str, "%f", f, &(f->val.c_float));
369 break;
370 case VAL_DOUBLE:
371 itemsMatched = sscanfWithNULL(str, "%lf", f, &(f->val.c_double));
372 break;
373 case VAL_BIGINT:
374 itemsMatched = sscanfWithNULL(str, "%Ld", f, &(f->val.c_int64));
375 break;
376 case VAL_TEXT:
377 f->val.c_ptr = str;
378 break;
379 case VAL_DATETIME:
380 case VAL_DATE: {
381 char *dateFormat = va_arg(ap, char*);
382 struct tm timeParts;
383 memset(&timeParts, 0, sizeof(struct tm));
384 char *res = strptime(str, dateFormat, &timeParts);
385 if (!res || *res) { /* strptime didn't consume string */
386 itemsMatched = 0;
387 } else {
388 f->val.time = mktime(&timeParts);
389 }}
390 break;
391 case VAL_JDATE: /* a julian day number to be dumped as a date */
392 itemsMatched = sscanf(str, "%lf", &(f->val.c_double));
393 break;
394 default:
395 abort();
396 }
397 va_end(ap);
398 if (itemsMatched!=1) {
399 handleBadRecord("fieldscanf: Can't parse field %s (value '%s')",
400 fieldName, str);
401 }
402 }
403
404
405
406 void writeHeader(void *destination)
407 {
408 char *header = "PGCOPY\n\377\r\n\0";
409 int32_t flags = 0;
410 int32_t headerLength = 0;
411
412 DATA_OUT(header, 11, destination);
413 DATA_OUT(&flags, 4, destination);
414 DATA_OUT(&headerLength, 4, destination);
415 }
416
417
418 void writeEndMarker(void *destination)
419 {
420 int16_t endMarker = -1;
421
422 endMarker = htons(endMarker);
423 DATA_OUT(&endMarker, 2, destination);
424 }
425
426
427 void writeBoolean(Field *field, void *destination)
428 {
429 char *head="\0\0\0\001";
430 DATA_OUT(head, 4, destination);
431 DATA_OUT(&(field->val.c_int8), 1, destination);
432 }
433
434 void writeShort(Field *field, void *destination)
435 {
436 char *head="\0\0\0\002";
437 uint16_t val=htons(field->val.c_int16);
438
439 DATA_OUT(head, 4, destination);
440 DATA_OUT(&val, 2, destination);
441 }
442
443 void writeInteger(Field *field, void *destination)
444 {
445 char *head="\0\0\0\004";
446 uint32_t val=htonl(field->val.c_int32);
447
448 DATA_OUT(head, 4, destination);
449 DATA_OUT(&val, 4, destination);
450 }
451
452
453 /* Complete insanity: Experimentally, it turns out that postgres wants
454 * the floats in inverse byte sequence compared to what you get on
455 * intel machines. This isn't really defined by IEEE, so this might
456 * not work for you.
457 */
458 void mirrorBytes(unsigned char *mem, int numBytes)
459 {
460 unsigned char *start = mem;
461 unsigned char *end = mem+numBytes-1;
462
463 if (__BYTE_ORDER==__BIG_ENDIAN) {
464 return;
465 }
466 while (start<end) {
467 char tmp=*start;
468 *start++ = *end;
469 *end-- = tmp;
470 }
471 }
472
473 void writeBigint(Field *field, void *destination)
474 {
475 uint32_t size=htonl(sizeof(int64_t));
476 int64_t val=field->val.c_int64;
477
478 mirrorBytes((unsigned char*)&val, sizeof(int64_t));
479 DATA_OUT(&size, 4, destination);
480 DATA_OUT(&val, sizeof(int64_t), destination);
481 }
482
483 void writeFloat(Field *field, void *destination)
484 {
485 uint32_t size=htonl(sizeof(float));
486 float val=field->val.c_float;
487
488 mirrorBytes((unsigned char*)&val, sizeof(float));
489 DATA_OUT(&size, 4, destination);
490 DATA_OUT(&val, sizeof(float), destination);
491 }
492
493 void writeDouble(Field *field, void *destination)
494 {
495 uint32_t size=htonl(sizeof(double));
496 double val=field->val.c_double;
497
498 mirrorBytes((unsigned char*)&val, sizeof(double));
499 DATA_OUT(&size, 4, destination);
500 DATA_OUT(&val, sizeof(double), destination);
501 }
502
503 void writeText(Field *field, void *destination)
504 {
505 int len=strlen(field->val.c_ptr);
506 uint32_t size=htonl(len);
507 DATA_OUT(&size, 4, destination);
508 DATA_OUT(field->val.c_ptr, len, destination);
509 }
510
511 double round(double val)
512 {
513 return floor(val+0.5);
514 }
515
516 /* Pg's dump has the number of days since the epoch 2000-01-01 for dates.
517 * 2451545.0 is noon UTC, 2001-01-01, the round adds 12 hours back and forth.
518 */
519 void writeJdate(Field *field, void *destination)
520 {
521 int32_t daysSinceEpoch=htonl(
522 (int32_t)(round(field->val.c_double-2451545.0)));
523 uint32_t size=htonl(sizeof(int32_t));
524
525 DATA_OUT(&size, 4, destination);
526 DATA_OUT(&daysSinceEpoch, sizeof(int32_t), destination);
527 }
528
529
530 void writeDate(Field *field, void *destination)
531 {
532 /* field->time is a unix time_t */
533 int32_t daysSinceEpoch=((field->val.time-PqEpoch)/86400);
534 uint32_t data=htonl(daysSinceEpoch);
535 uint32_t size=htonl(sizeof(int32_t));
536
537 /* fprintf(stderr, "dse: %d\n", daysSinceEpoch);*/
538 DATA_OUT(&size, 4, destination);
539 DATA_OUT(&data, sizeof(uint32_t), destination);
540 }
541
542
543 /* Array writing is generic here: We expect other elements to already
544 have serialised the array to a contiguous array of bytes */
545 void writeArray(Field *field, void *destination)
546 {
547 uint32_t size=htonl(field->length);
548 DATA_OUT(&size, 4, destination);
549 DATA_OUT(field->val.arr_ptr, field->length, destination);
550 }
551
552
553 /* packArray takes nVals values of length itemsize from vals.
554 It writes the bytes for a postgres dump of them into buf.
555 Buf needs at least nVals*(4+itemsize)+36 bytes, and the function
556 will recklessly buffer overflow if you don't provide
557 it. This returns the number for bytes written into buf.
558
559 See below for what I'm writing; this is based on
560 backend/utils/adt/arrayfuncs.c of the postgres source and puzzling
561 over an actual dump. */
562 size_t packArray(
563 unsigned char *buf, /* the target buffer */
564 unsigned char *vals, /* the values to serialise */
565 int nVals, /* number of items in vals */
566 int itemoid, /* postgres UID of the target type */
567 size_t itemsize, /* size of each item in vals */
568 int littleEndian /* have this 1 when incoming data is little-endian */
569 )
570 {
571 unsigned char *wp=buf;
572 uint32_t intbuf;
573 int i;
574
575 /* (1) 32 bits of number of dimensions */
576 intbuf = htonl(1);
577 ADD_DATA(&intbuf, 4, wp);
578
579 /* (2) a 32 bit zero, indicating there are no null values here
580 (I can't do them) */
581 intbuf = 0;
582 ADD_DATA(&intbuf, 4, wp);
583
584 /* (3) The oid. */
585 intbuf = htonl(itemoid);
586 ADD_DATA(&intbuf, 4, wp);
587
588 /* (4) 32 bits of the the number of elements */
589 intbuf = htonl(nVals);
590 ADD_DATA(&intbuf, 4, wp);
591
592 /* (5) a 32 bit 1, for the lower bound of the array */
593 intbuf = htonl(1);
594 ADD_DATA(&intbuf, 4, wp);
595
596 /* (6) for each element, 32 bits of item size, and then item's bytes. */
597 for (i=0; i<nVals; i++) {
598 unsigned char *val = vals+i*itemsize;
599 intbuf = htonl(itemsize);
600 ADD_DATA(&intbuf, 4, wp);
601 if (littleEndian) {
602 mirrorBytes(val, itemsize);
603 }
604 ADD_DATA(val, itemsize, wp);
605 }
606
607 return wp-buf;
608 }
609
610 void writeDatetime(Field *field, void *destination)
611 { /* it seems postgres stores dates and times either in int64s or in
612 something else :-). Well, I take the int64 thing here, and there,
613 I guess it's just the number of microseconds since the epoch. */
614 #ifdef HAVE_INT64_TIMESTAMP
615 int64_t usecsSinceEpoch = (field->val.time-PqEpoch);
616 uint32_t size = sizeof(int64_t);
617 usecsSinceEpoch *= 1000000;
618 #else
619 double usecsSinceEpoch = (field->val.time-PqEpoch);
620 uint32_t size = sizeof(double);
621 #endif
622 uint32_t size_n=htonl(size);
623
624 mirrorBytes((unsigned char*)&usecsSinceEpoch, size);
625 DATA_OUT(&size_n, 4, destination);
626 DATA_OUT(&usecsSinceEpoch, size, destination);
627 }
628
629
630 void writeField(Field *field, void *destination)
631 {
632 int32_t nullValue = htonl(-1);
633
634 switch (field->type) {
635 case VAL_NULL:
636 DATA_OUT(&nullValue, 4, destination);
637 break;
638 case VAL_BOOL:
639 writeBoolean(field, destination);
640 break;
641 case VAL_CHAR:
642 writeBoolean(field, destination);
643 break;
644 case VAL_SHORT:
645 writeShort(field, destination);
646 break;
647 case VAL_INT:
648 writeInteger(field, destination);
649 break;
650 case VAL_BIGINT:
651 writeBigint(field, destination);
652 break;
653 case VAL_FLOAT:
654 writeFloat(field, destination);
655 break;
656 case VAL_DOUBLE:
657 writeDouble(field, destination);
658 break;
659 case VAL_TEXT:
660 writeText(field, destination);
661 break;
662 case VAL_JDATE:
663 writeJdate(field, destination);
664 break;
665 case VAL_DATE:
666 writeDate(field, destination);
667 break;
668 case VAL_DATETIME:
669 writeDatetime(field, destination);
670 break;
671 case VAL_ARRAY:
672 writeArray(field, destination);
673 break;
674 default:
675 die("Unknown type code: %d\n", field->type);
676 }
677 }
678
679 void writeTuple(Field *fields, int numFields, void *destination)
680 {
681 Field *curField;
682 int16_t fieldCount=htons(numFields);
683
684 DATA_OUT(&fieldCount, 2, destination);
685 for (curField=fields; curField-fields<numFields; curField++) {
686 writeField(curField, destination);
687 }
688 }
689
690
691 int degToHms(double deg,
692 int *hours_out, int *minutes_out, double *seconds_out)
693 {
694 double rest, ipart;
695
696 while (deg<0) {
697 deg += 360;
698 }
699 rest = modf(deg/360.*24, &ipart);
700 *hours_out = (int)ipart;
701 rest = modf(rest*60, &ipart);
702 *minutes_out = (int)ipart;
703 *seconds_out = rest*60;
704 return 0;
705 }
706
707
708 int degToDms(double deg, char *sign_out,
709 int *degs_out, int *minutes_out, double *seconds_out)
710 {
711 double rest, ipart;
712
713 *sign_out = '+';
714 if (deg<0) {
715 *sign_out = '-';
716 deg = -deg;
717 }
718 rest = modf(deg, &ipart);
719 *degs_out = (int)ipart;
720 rest = modf(rest*60, &ipart);
721 *minutes_out = (int)ipart;
722 *seconds_out = rest*60;
723 return 0;
724 }
725
726
727 double jYearToJDN(double jYear)
728 {
729 return (jYear-2000)*365.25+2451545.0;
730 }
731
732
733 char *strtok_u(char *arg, char *separator) {
734 /* like strtok, but doesn't merge adjacent separators */
735 static char *cur;
736 char *next, *res;
737
738 if (arg!=NULL) {
739 cur = arg;
740 }
741
742 if (*cur=='\0') {
743 /* we are at the and of the input */
744 return NULL;
745 }
746 next = strstr(cur, separator);
747 if (next==NULL) {
748 /* No separator token found; return what's left of the string and
749 move cur to the end */
750 res = cur;
751 cur += strlen(cur);
752 } else {
753 /* normal case: return from old cur to the start of the separator.
754 Then let cur point to the start of what's left of the string after
755 the current separator token */
756 res = cur;
757 cur = next+strlen(separator);
758 *next = 0;
759 }
760 return res;
761 }
762
763 int main(int argc, char **argv)
764 {
765 PqEpoch = mktime(&pqEpochParts);
766 createDumpfile(argc, argv);
767 return 0;
768 }
769