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