| | 3439 | |
| | 3440 | PG_FUNCTION_INFO_V1(ST_CollectionExtract); |
| | 3441 | Datum ST_CollectionExtract(PG_FUNCTION_ARGS) |
| | 3442 | { |
| | 3443 | PG_LWGEOM *input = (PG_LWGEOM *)PG_DETOAST_DATUM(PG_GETARG_DATUM(0)); |
| | 3444 | PG_LWGEOM *output; |
| | 3445 | LWGEOM *lwgeom = pglwgeom_deserialize(input); |
| | 3446 | LWCOLLECTION *lwcol = NULL; |
| | 3447 | int type = PG_GETARG_INT32(1); |
| | 3448 | int lwgeom_type = TYPE_GETTYPE(lwgeom->type); |
| | 3449 | |
| | 3450 | /* Ensure the right type was input */ |
| | 3451 | if ( ! ( type == POINTTYPE || type == LINETYPE || type == POLYGONTYPE ) ) |
| | 3452 | { |
| | 3453 | lwgeom_free(lwgeom); |
| | 3454 | elog(ERROR, "ST_CollectionExtract: only point, linestring and polygon may be extracted"); |
| | 3455 | PG_RETURN_NULL(); |
| | 3456 | } |
| | 3457 | |
| | 3458 | /* Mirror non-collections right back */ |
| | 3459 | if ( ! lwgeom_is_collection(lwgeom_type) ) |
| | 3460 | { |
| | 3461 | output = palloc(VARSIZE(input)); |
| | 3462 | memcpy(VARDATA(output), VARDATA(input), VARSIZE(input) - VARHDRSZ); |
| | 3463 | SET_VARSIZE(output, VARSIZE(input)); |
| | 3464 | lwgeom_free(lwgeom); |
| | 3465 | PG_RETURN_POINTER(output); |
| | 3466 | } |
| | 3467 | |
| | 3468 | lwcol = lwcollection_extract((LWCOLLECTION*)lwgeom, type); |
| | 3469 | output = pglwgeom_serialize((LWGEOM*)lwcol); |
| | 3470 | lwgeom_free(lwgeom); |
| | 3471 | |
| | 3472 | PG_RETURN_POINTER(output); |
| | 3473 | } |