]> granicus.if.org Git - postgresql/blob - src/test/regress/regress.c
Sequences are now based on int8, not int4, arithmetic. SERIAL pseudo-type
[postgresql] / src / test / regress / regress.c
1 /*
2  * $Header: /cvsroot/pgsql/src/test/regress/regress.c,v 1.48 2001/08/16 20:38:56 tgl Exp $
3  */
4
5 #include "postgres.h"
6
7 #include <float.h>                              /* faked on sunos */
8
9 #include "utils/geo_decls.h"    /* includes <math.h> */
10 #include "executor/executor.h"  /* For GetAttributeByName */
11 #include "commands/sequence.h"  /* for nextval() */
12
13 #define P_MAXDIG 12
14 #define LDELIM                  '('
15 #define RDELIM                  ')'
16 #define DELIM                   ','
17
18 typedef TupleTableSlot *TUPLE;
19
20 extern Datum regress_dist_ptpath(PG_FUNCTION_ARGS);
21 extern Datum regress_path_dist(PG_FUNCTION_ARGS);
22 extern PATH *poly2path(POLYGON *poly);
23 extern Datum interpt_pp(PG_FUNCTION_ARGS);
24 extern void regress_lseg_construct(LSEG *lseg, Point *pt1, Point *pt2);
25 extern Datum overpaid(PG_FUNCTION_ARGS);
26 extern Datum boxarea(PG_FUNCTION_ARGS);
27 extern char *reverse_name(char *string);
28 extern int      oldstyle_length(int n, text *t);
29
30 /*
31 ** Distance from a point to a path
32 */
33 PG_FUNCTION_INFO_V1(regress_dist_ptpath);
34
35 Datum
36 regress_dist_ptpath(PG_FUNCTION_ARGS)
37 {
38         Point      *pt = PG_GETARG_POINT_P(0);
39         PATH       *path = PG_GETARG_PATH_P(1);
40         float8          result = 0.0;   /* keep compiler quiet */
41         float8          tmp;
42         int                     i;
43         LSEG            lseg;
44
45         switch (path->npts)
46         {
47                 case 0:
48                         PG_RETURN_NULL();
49                 case 1:
50                         result = point_dt(pt, &path->p[0]);
51                         break;
52                 default:
53
54                         /*
55                          * the distance from a point to a path is the smallest
56                          * distance from the point to any of its constituent segments.
57                          */
58                         Assert(path->npts > 1);
59                         for (i = 0; i < path->npts - 1; ++i)
60                         {
61                                 regress_lseg_construct(&lseg, &path->p[i], &path->p[i + 1]);
62                                 tmp = DatumGetFloat8(DirectFunctionCall2(dist_ps,
63                                                                                                           PointPGetDatum(pt),
64                                                                                                   LsegPGetDatum(&lseg)));
65                                 if (i == 0 || tmp < result)
66                                         result = tmp;
67                         }
68                         break;
69         }
70         PG_RETURN_FLOAT8(result);
71 }
72
73 /* this essentially does a cartesian product of the lsegs in the
74    two paths, and finds the min distance between any two lsegs */
75 PG_FUNCTION_INFO_V1(regress_path_dist);
76
77 Datum
78 regress_path_dist(PG_FUNCTION_ARGS)
79 {
80         PATH       *p1 = PG_GETARG_PATH_P(0);
81         PATH       *p2 = PG_GETARG_PATH_P(1);
82         bool            have_min = false;
83         float8          min = 0.0;              /* initialize to keep compiler quiet */
84         float8          tmp;
85         int                     i,
86                                 j;
87         LSEG            seg1,
88                                 seg2;
89
90         for (i = 0; i < p1->npts - 1; i++)
91         {
92                 for (j = 0; j < p2->npts - 1; j++)
93                 {
94                         regress_lseg_construct(&seg1, &p1->p[i], &p1->p[i + 1]);
95                         regress_lseg_construct(&seg2, &p2->p[j], &p2->p[j + 1]);
96
97                         tmp = DatumGetFloat8(DirectFunctionCall2(lseg_distance,
98                                                                                                          LsegPGetDatum(&seg1),
99                                                                                                   LsegPGetDatum(&seg2)));
100                         if (!have_min || tmp < min)
101                         {
102                                 min = tmp;
103                                 have_min = true;
104                         }
105                 }
106         }
107
108         if (!have_min)
109                 PG_RETURN_NULL();
110
111         PG_RETURN_FLOAT8(min);
112 }
113
114 PATH *
115 poly2path(poly)
116 POLYGON    *poly;
117 {
118         int                     i;
119         char       *output = (char *) palloc(2 * (P_MAXDIG + 1) * poly->npts + 64);
120         char            buf[2 * (P_MAXDIG) + 20];
121
122         sprintf(output, "(1, %*d", P_MAXDIG, poly->npts);
123
124         for (i = 0; i < poly->npts; i++)
125         {
126                 sprintf(buf, ",%*g,%*g", P_MAXDIG, poly->p[i].x, P_MAXDIG, poly->p[i].y);
127                 strcat(output, buf);
128         }
129
130         sprintf(buf, "%c", RDELIM);
131         strcat(output, buf);
132         return DatumGetPathP(DirectFunctionCall1(path_in,
133                                                                                          CStringGetDatum(output)));
134 }
135
136 /* return the point where two paths intersect, or NULL if no intersection. */
137 PG_FUNCTION_INFO_V1(interpt_pp);
138
139 Datum
140 interpt_pp(PG_FUNCTION_ARGS)
141 {
142         PATH       *p1 = PG_GETARG_PATH_P(0);
143         PATH       *p2 = PG_GETARG_PATH_P(1);
144         int                     i,
145                                 j;
146         LSEG            seg1,
147                                 seg2;
148         bool            found;                  /* We've found the intersection */
149
150         found = false;                          /* Haven't found it yet */
151
152         for (i = 0; i < p1->npts - 1 && !found; i++)
153         {
154                 regress_lseg_construct(&seg1, &p1->p[i], &p1->p[i + 1]);
155                 for (j = 0; j < p2->npts - 1 && !found; j++)
156                 {
157                         regress_lseg_construct(&seg2, &p2->p[j], &p2->p[j + 1]);
158                         if (DatumGetBool(DirectFunctionCall2(lseg_intersect,
159                                                                                                  LsegPGetDatum(&seg1),
160                                                                                                  LsegPGetDatum(&seg2))))
161                                 found = true;
162                 }
163         }
164
165         if (!found)
166                 PG_RETURN_NULL();
167
168         /*
169          * Note: DirectFunctionCall2 will kick out an error if lseg_interpt()
170          * returns NULL, but that should be impossible since we know the two
171          * segments intersect.
172          */
173         PG_RETURN_DATUM(DirectFunctionCall2(lseg_interpt,
174                                                                                 LsegPGetDatum(&seg1),
175                                                                                 LsegPGetDatum(&seg2)));
176 }
177
178
179 /* like lseg_construct, but assume space already allocated */
180 void
181 regress_lseg_construct(lseg, pt1, pt2)
182 LSEG       *lseg;
183 Point      *pt1;
184 Point      *pt2;
185 {
186         lseg->p[0].x = pt1->x;
187         lseg->p[0].y = pt1->y;
188         lseg->p[1].x = pt2->x;
189         lseg->p[1].y = pt2->y;
190         lseg->m = point_sl(pt1, pt2);
191 }
192
193 PG_FUNCTION_INFO_V1(overpaid);
194
195 Datum
196 overpaid(PG_FUNCTION_ARGS)
197 {
198         TUPLE           tuple = (TUPLE) PG_GETARG_POINTER(0);
199         bool            isnull;
200         int32           salary;
201
202         salary = DatumGetInt32(GetAttributeByName(tuple, "salary", &isnull));
203         if (isnull)
204                 PG_RETURN_NULL();
205         PG_RETURN_BOOL(salary > 699);
206 }
207
208 /* New type "widget"
209  * This used to be "circle", but I added circle to builtins,
210  *      so needed to make sure the names do not collide. - tgl 97/04/21
211  */
212
213 typedef struct
214 {
215         Point           center;
216         double          radius;
217 }                       WIDGET;
218
219 WIDGET     *widget_in(char *str);
220 char       *widget_out(WIDGET * widget);
221 extern Datum pt_in_widget(PG_FUNCTION_ARGS);
222
223 #define NARGS   3
224
225 WIDGET *
226 widget_in(str)
227 char       *str;
228 {
229         char       *p,
230                            *coord[NARGS],
231                                 buf2[1000];
232         int                     i;
233         WIDGET     *result;
234
235         if (str == NULL)
236                 return NULL;
237         for (i = 0, p = str; *p && i < NARGS && *p != RDELIM; p++)
238                 if (*p == ',' || (*p == LDELIM && !i))
239                         coord[i++] = p + 1;
240         if (i < NARGS - 1)
241                 return NULL;
242         result = (WIDGET *) palloc(sizeof(WIDGET));
243         result->center.x = atof(coord[0]);
244         result->center.y = atof(coord[1]);
245         result->radius = atof(coord[2]);
246
247         sprintf(buf2, "widget_in: read (%f, %f, %f)\n", result->center.x,
248                         result->center.y, result->radius);
249         return result;
250 }
251
252 char *
253 widget_out(widget)
254 WIDGET     *widget;
255 {
256         char       *result;
257
258         if (widget == NULL)
259                 return NULL;
260
261         result = (char *) palloc(60);
262         sprintf(result, "(%g,%g,%g)",
263                         widget->center.x, widget->center.y, widget->radius);
264         return result;
265 }
266
267 PG_FUNCTION_INFO_V1(pt_in_widget);
268
269 Datum
270 pt_in_widget(PG_FUNCTION_ARGS)
271 {
272         Point      *point = PG_GETARG_POINT_P(0);
273         WIDGET     *widget = (WIDGET *) PG_GETARG_POINTER(1);
274
275         PG_RETURN_BOOL(point_dt(point, &widget->center) < widget->radius);
276 }
277
278 #define ABS(X) ((X) >= 0 ? (X) : -(X))
279
280 PG_FUNCTION_INFO_V1(boxarea);
281
282 Datum
283 boxarea(PG_FUNCTION_ARGS)
284 {
285         BOX                *box = PG_GETARG_BOX_P(0);
286         double          width,
287                                 height;
288
289         width = ABS(box->high.x - box->low.x);
290         height = ABS(box->high.y - box->low.y);
291         PG_RETURN_FLOAT8(width * height);
292 }
293
294 char *
295 reverse_name(char *string)
296 {
297         int                     i;
298         int                     len;
299         char       *new_string;
300
301         if (!(new_string = palloc(NAMEDATALEN)))
302         {
303                 fprintf(stderr, "reverse_name: palloc failed\n");
304                 return NULL;
305         }
306         MemSet(new_string, 0, NAMEDATALEN);
307         for (i = 0; i < NAMEDATALEN && string[i]; ++i)
308                 ;
309         if (i == NAMEDATALEN || !string[i])
310                 --i;
311         len = i;
312         for (; i >= 0; --i)
313                 new_string[len - i] = string[i];
314         return new_string;
315 }
316
317 /* This rather silly function is just to test that oldstyle functions
318  * work correctly on toast-able inputs.
319  */
320 int
321 oldstyle_length(int n, text *t)
322 {
323         int                     len = 0;
324
325         if (t)
326                 len = VARSIZE(t) - VARHDRSZ;
327
328         return n + len;
329 }
330
331 #include "executor/spi.h"               /* this is what you need to work with SPI */
332 #include "commands/trigger.h"   /* -"- and triggers */
333
334 static TransactionId fd17b_xid = InvalidTransactionId;
335 static TransactionId fd17a_xid = InvalidTransactionId;
336 static int      fd17b_level = 0;
337 static int      fd17a_level = 0;
338 static bool fd17b_recursion = true;
339 static bool fd17a_recursion = true;
340 extern Datum funny_dup17(PG_FUNCTION_ARGS);
341
342 PG_FUNCTION_INFO_V1(funny_dup17);
343
344 Datum
345 funny_dup17(PG_FUNCTION_ARGS)
346 {
347         TriggerData *trigdata = (TriggerData *) fcinfo->context;
348         TransactionId *xid;
349         int                *level;
350         bool       *recursion;
351         Relation        rel;
352         TupleDesc       tupdesc;
353         HeapTuple       tuple;
354         char       *query,
355                            *fieldval,
356                            *fieldtype;
357         char       *when;
358         int                     inserted;
359         int                     selected = 0;
360         int                     ret;
361
362         if (!CALLED_AS_TRIGGER(fcinfo))
363                 elog(ERROR, "funny_dup17: not fired by trigger manager");
364
365         tuple = trigdata->tg_trigtuple;
366         rel = trigdata->tg_relation;
367         tupdesc = rel->rd_att;
368         if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
369         {
370                 xid = &fd17b_xid;
371                 level = &fd17b_level;
372                 recursion = &fd17b_recursion;
373                 when = "BEFORE";
374         }
375         else
376         {
377                 xid = &fd17a_xid;
378                 level = &fd17a_level;
379                 recursion = &fd17a_recursion;
380                 when = "AFTER ";
381         }
382
383         if (!TransactionIdIsCurrentTransactionId(*xid))
384         {
385                 *xid = GetCurrentTransactionId();
386                 *level = 0;
387                 *recursion = true;
388         }
389
390         if (*level == 17)
391         {
392                 *recursion = false;
393                 return PointerGetDatum(tuple);
394         }
395
396         if (!(*recursion))
397                 return PointerGetDatum(tuple);
398
399         (*level)++;
400
401         SPI_connect();
402
403         fieldval = SPI_getvalue(tuple, tupdesc, 1);
404         fieldtype = SPI_gettype(tupdesc, 1);
405
406         query = (char *) palloc(100 + NAMEDATALEN * 3 +
407                                                         strlen(fieldval) + strlen(fieldtype));
408
409         sprintf(query, "insert into %s select * from %s where %s = '%s'::%s",
410                         SPI_getrelname(rel), SPI_getrelname(rel),
411                         SPI_fname(tupdesc, 1),
412                         fieldval, fieldtype);
413
414         if ((ret = SPI_exec(query, 0)) < 0)
415                 elog(ERROR, "funny_dup17 (fired %s) on level %3d: SPI_exec (insert ...) returned %d",
416                          when, *level, ret);
417
418         inserted = SPI_processed;
419
420         sprintf(query, "select count (*) from %s where %s = '%s'::%s",
421                         SPI_getrelname(rel),
422                         SPI_fname(tupdesc, 1),
423                         fieldval, fieldtype);
424
425         if ((ret = SPI_exec(query, 0)) < 0)
426                 elog(ERROR, "funny_dup17 (fired %s) on level %3d: SPI_exec (select ...) returned %d",
427                          when, *level, ret);
428
429         if (SPI_processed > 0)
430         {
431                 selected = DatumGetInt32(DirectFunctionCall1(int4in,
432                                                                                         CStringGetDatum(SPI_getvalue(
433                                                                                                    SPI_tuptable->vals[0],
434                                                                                                    SPI_tuptable->tupdesc,
435                                                                                                                                                  1
436                                                                                                                                         ))));
437         }
438
439         elog(NOTICE, "funny_dup17 (fired %s) on level %3d: %d/%d tuples inserted/selected",
440                  when, *level, inserted, selected);
441
442         SPI_finish();
443
444         (*level)--;
445
446         if (*level == 0)
447                 *xid = InvalidTransactionId;
448
449         return PointerGetDatum(tuple);
450 }
451
452 extern Datum ttdummy(PG_FUNCTION_ARGS);
453 extern Datum set_ttdummy(PG_FUNCTION_ARGS);
454
455 #define TTDUMMY_INFINITY        999999
456
457 static void *splan = NULL;
458 static bool ttoff = false;
459
460 PG_FUNCTION_INFO_V1(ttdummy);
461
462 Datum
463 ttdummy(PG_FUNCTION_ARGS)
464 {
465         TriggerData *trigdata = (TriggerData *) fcinfo->context;
466         Trigger    *trigger;            /* to get trigger name */
467         char      **args;                       /* arguments */
468         int                     attnum[2];              /* fnumbers of start/stop columns */
469         Datum           oldon,
470                                 oldoff;
471         Datum           newon,
472                                 newoff;
473         Datum      *cvals;                      /* column values */
474         char       *cnulls;                     /* column nulls */
475         char       *relname;            /* triggered relation name */
476         Relation        rel;                    /* triggered relation */
477         HeapTuple       trigtuple;
478         HeapTuple       newtuple = NULL;
479         HeapTuple       rettuple;
480         TupleDesc       tupdesc;                /* tuple description */
481         int                     natts;                  /* # of attributes */
482         bool            isnull;                 /* to know is some column NULL or not */
483         int                     ret;
484         int                     i;
485
486         if (!CALLED_AS_TRIGGER(fcinfo))
487                 elog(ERROR, "ttdummy: not fired by trigger manager");
488         if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
489                 elog(ERROR, "ttdummy: can't process STATEMENT events");
490         if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
491                 elog(ERROR, "ttdummy: must be fired before event");
492         if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
493                 elog(ERROR, "ttdummy: can't process INSERT event");
494         if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
495                 newtuple = trigdata->tg_newtuple;
496
497         trigtuple = trigdata->tg_trigtuple;
498
499         rel = trigdata->tg_relation;
500         relname = SPI_getrelname(rel);
501
502         /* check if TT is OFF for this relation */
503         if (ttoff)                                      /* OFF - nothing to do */
504         {
505                 pfree(relname);
506                 return PointerGetDatum((newtuple != NULL) ? newtuple : trigtuple);
507         }
508
509         trigger = trigdata->tg_trigger;
510
511         if (trigger->tgnargs != 2)
512                 elog(ERROR, "ttdummy (%s): invalid (!= 2) number of arguments %d",
513                          relname, trigger->tgnargs);
514
515         args = trigger->tgargs;
516         tupdesc = rel->rd_att;
517         natts = tupdesc->natts;
518
519         for (i = 0; i < 2; i++)
520         {
521                 attnum[i] = SPI_fnumber(tupdesc, args[i]);
522                 if (attnum[i] < 0)
523                         elog(ERROR, "ttdummy (%s): there is no attribute %s", relname, args[i]);
524                 if (SPI_gettypeid(tupdesc, attnum[i]) != INT4OID)
525                         elog(ERROR, "ttdummy (%s): attributes %s and %s must be of abstime type",
526                                  relname, args[0], args[1]);
527         }
528
529         oldon = SPI_getbinval(trigtuple, tupdesc, attnum[0], &isnull);
530         if (isnull)
531                 elog(ERROR, "ttdummy (%s): %s must be NOT NULL", relname, args[0]);
532
533         oldoff = SPI_getbinval(trigtuple, tupdesc, attnum[1], &isnull);
534         if (isnull)
535                 elog(ERROR, "ttdummy (%s): %s must be NOT NULL", relname, args[1]);
536
537         if (newtuple != NULL)           /* UPDATE */
538         {
539                 newon = SPI_getbinval(newtuple, tupdesc, attnum[0], &isnull);
540                 if (isnull)
541                         elog(ERROR, "ttdummy (%s): %s must be NOT NULL", relname, args[0]);
542                 newoff = SPI_getbinval(newtuple, tupdesc, attnum[1], &isnull);
543                 if (isnull)
544                         elog(ERROR, "ttdummy (%s): %s must be NOT NULL", relname, args[1]);
545
546                 if (oldon != newon || oldoff != newoff)
547                         elog(ERROR, "ttdummy (%s): you can't change %s and/or %s columns (use set_ttdummy)",
548                                  relname, args[0], args[1]);
549
550                 if (newoff != TTDUMMY_INFINITY)
551                 {
552                         pfree(relname);         /* allocated in upper executor context */
553                         return PointerGetDatum(NULL);
554                 }
555         }
556         else if (oldoff != TTDUMMY_INFINITY)            /* DELETE */
557         {
558                 pfree(relname);
559                 return PointerGetDatum(NULL);
560         }
561
562         {
563                 text       *seqname = DatumGetTextP(DirectFunctionCall1(textin,
564                                                                                 CStringGetDatum("ttdummy_seq")));
565
566                 newoff = DirectFunctionCall1(nextval,
567                                                                          PointerGetDatum(seqname));
568                 /* nextval now returns int64; coerce down to int32 */
569                 newoff = Int32GetDatum((int32) DatumGetInt64(newoff));
570                 pfree(seqname);
571         }
572
573         /* Connect to SPI manager */
574         if ((ret = SPI_connect()) < 0)
575                 elog(ERROR, "ttdummy (%s): SPI_connect returned %d", relname, ret);
576
577         /* Fetch tuple values and nulls */
578         cvals = (Datum *) palloc(natts * sizeof(Datum));
579         cnulls = (char *) palloc(natts * sizeof(char));
580         for (i = 0; i < natts; i++)
581         {
582                 cvals[i] = SPI_getbinval((newtuple != NULL) ? newtuple : trigtuple,
583                                                                  tupdesc, i + 1, &isnull);
584                 cnulls[i] = (isnull) ? 'n' : ' ';
585         }
586
587         /* change date column(s) */
588         if (newtuple)                           /* UPDATE */
589         {
590                 cvals[attnum[0] - 1] = newoff;  /* start_date eq current date */
591                 cnulls[attnum[0] - 1] = ' ';
592                 cvals[attnum[1] - 1] = TTDUMMY_INFINITY;                /* stop_date eq INFINITY */
593                 cnulls[attnum[1] - 1] = ' ';
594         }
595         else
596 /* DELETE */
597         {
598                 cvals[attnum[1] - 1] = newoff;  /* stop_date eq current date */
599                 cnulls[attnum[1] - 1] = ' ';
600         }
601
602         /* if there is no plan ... */
603         if (splan == NULL)
604         {
605                 void       *pplan;
606                 Oid                *ctypes;
607                 char       *query;
608
609                 /* allocate space in preparation */
610                 ctypes = (Oid *) palloc(natts * sizeof(Oid));
611                 query = (char *) palloc(100 + 16 * natts);
612
613                 /*
614                  * Construct query: INSERT INTO _relation_ VALUES ($1, ...)
615                  */
616                 sprintf(query, "INSERT INTO %s VALUES (", relname);
617                 for (i = 1; i <= natts; i++)
618                 {
619                         sprintf(query + strlen(query), "$%d%s",
620                                         i, (i < natts) ? ", " : ")");
621                         ctypes[i - 1] = SPI_gettypeid(tupdesc, i);
622                 }
623
624                 /* Prepare plan for query */
625                 pplan = SPI_prepare(query, natts, ctypes);
626                 if (pplan == NULL)
627                         elog(ERROR, "ttdummy (%s): SPI_prepare returned %d", relname, SPI_result);
628
629                 pplan = SPI_saveplan(pplan);
630                 if (pplan == NULL)
631                         elog(ERROR, "ttdummy (%s): SPI_saveplan returned %d", relname, SPI_result);
632
633                 splan = pplan;
634         }
635
636         ret = SPI_execp(splan, cvals, cnulls, 0);
637
638         if (ret < 0)
639                 elog(ERROR, "ttdummy (%s): SPI_execp returned %d", relname, ret);
640
641         /* Tuple to return to upper Executor ... */
642         if (newtuple)                           /* UPDATE */
643         {
644                 HeapTuple       tmptuple;
645
646                 tmptuple = SPI_copytuple(trigtuple);
647                 rettuple = SPI_modifytuple(rel, tmptuple, 1, &(attnum[1]), &newoff, NULL);
648                 SPI_freetuple(tmptuple);
649         }
650         else
651 /* DELETE */
652                 rettuple = trigtuple;
653
654         SPI_finish();                           /* don't forget say Bye to SPI mgr */
655
656         pfree(relname);
657
658         return PointerGetDatum(rettuple);
659 }
660
661 PG_FUNCTION_INFO_V1(set_ttdummy);
662
663 Datum
664 set_ttdummy(PG_FUNCTION_ARGS)
665 {
666         int32           on = PG_GETARG_INT32(0);
667
668         if (ttoff)                                      /* OFF currently */
669         {
670                 if (on == 0)
671                         PG_RETURN_INT32(0);
672
673                 /* turn ON */
674                 ttoff = false;
675                 PG_RETURN_INT32(0);
676         }
677
678         /* ON currently */
679         if (on != 0)
680                 PG_RETURN_INT32(1);
681
682         /* turn OFF */
683         ttoff = true;
684
685         PG_RETURN_INT32(1);
686 }