if (entry->leafkey)
{
TSKEY *r = (TSKEY *) palloc(sizeof(TSKEY));
+
retval = palloc(sizeof(GISTENTRY));
r->lower = r->upper = *(Timestamp *) (entry->key);
gistentryinit(*retval, PointerGetDatum(r),
- entry->rel, entry->page,
- entry->offset, sizeof(TSKEY), FALSE);
+ entry->rel, entry->page,
+ entry->offset, sizeof(TSKEY), FALSE);
}
else
retval = entry;
intr = DatumGetIntervalP(DirectFunctionCall2(
timestamp_mi,
- TimestampGetDatumFast(newentry->upper),
- TimestampGetDatumFast(origentry->upper)));
+ TimestampGetDatumFast(newentry->upper),
+ TimestampGetDatumFast(origentry->upper)));
/* see interval_larger */
*result = Max(intr->time + intr->month * (30.0 * 86400), 0);
intr = DatumGetIntervalP(DirectFunctionCall2(
timestamp_mi,
- TimestampGetDatumFast(origentry->lower),
- TimestampGetDatumFast(newentry->lower)));
+ TimestampGetDatumFast(origentry->lower),
+ TimestampGetDatumFast(newentry->lower)));
/* see interval_larger */
*result += Max(intr->time + intr->month * (30.0 * 86400), 0);
return DatumGetInt32(
DirectFunctionCall2(
timestamp_cmp,
- TimestampGetDatumFast(((TSKEY *) (((RIX *) a)->r))->lower),
- TimestampGetDatumFast(((TSKEY *) (((RIX *) b)->r))->lower)
+ TimestampGetDatumFast(((TSKEY *) (((RIX *) a)->r))->lower),
+ TimestampGetDatumFast(((TSKEY *) (((RIX *) b)->r))->lower)
)
);
}
bool cube_lt(NDBOX * a, NDBOX * b);
bool cube_gt(NDBOX * a, NDBOX * b);
double *cube_distance(NDBOX * a, NDBOX * b);
-int cube_dim(NDBOX *a);
-double *cube_ll_coord(NDBOX * a, int n);
-double *cube_ur_coord(NDBOX * a, int n);
-bool cube_is_point(NDBOX * a);
-NDBOX *cube_enlarge(NDBOX * a, double * r, int n);
+int cube_dim(NDBOX * a);
+double *cube_ll_coord(NDBOX * a, int n);
+double *cube_ur_coord(NDBOX * a, int n);
+bool cube_is_point(NDBOX * a);
+NDBOX *cube_enlarge(NDBOX * a, double *r, int n);
/*
cube(text *str)
{
return cube_in(DatumGetCString(DirectFunctionCall1(textout,
- PointerGetDatum(str))));
+ PointerGetDatum(str))));
}
char *
-cube_out(NDBOX *cube)
+cube_out(NDBOX * cube)
{
StringInfoData buf;
bool equal = true;
if (a->dim >= b->dim)
{
result = palloc(a->size);
- memset(result, 0, a->size);
+ memset(result, 0, a->size);
result->size = a->size;
result->dim = a->dim;
}
else
{
result = palloc(b->size);
- memset(result, 0, b->size);
+ memset(result, 0, b->size);
result->size = b->size;
result->dim = b->dim;
}
/* compute the union */
for (i = 0; i < a->dim; i++)
- {
+ {
result->x[i] =
- min(min(a->x[i], a->x[i + a->dim]), result->x[i]);
+ min(min(a->x[i], a->x[i + a->dim]), result->x[i]);
result->x[i + a->dim] = max(max(a->x[i],
- a->x[i + a->dim]), result->x[i + a->dim]);
- }
+ a->x[i + a->dim]), result->x[i + a->dim]);
+ }
return (result);
}
if (a->dim >= b->dim)
{
result = palloc(a->size);
- memset(result, 0, a->size);
+ memset(result, 0, a->size);
result->size = a->size;
result->dim = a->dim;
}
else
{
result = palloc(b->size);
- memset(result, 0, b->size);
+ memset(result, 0, b->size);
result->size = b->size;
result->dim = b->dim;
}
/* compute the intersection */
for (i = 0; i < a->dim; i++)
- {
+ {
result->x[i] =
- max(min(a->x[i], a->x[i + a->dim]), result->x[i]);
+ max(min(a->x[i], a->x[i + a->dim]), result->x[i]);
result->x[i + a->dim] = min(max(a->x[i],
- a->x[i + a->dim]), result->x[i + a->dim]);
- }
+ a->x[i + a->dim]), result->x[i + a->dim]);
+ }
/*
* Is it OK to return a non-null intersection for non-overlapping
return (FALSE);
return (min(a->x[a->dim - 1], a->x[2 * a->dim - 1]) <=
- min(b->x[b->dim - 1], b->x[2 * b->dim - 1]) &&
- !cube_left(a, b) && !cube_right(a, b));
+ min(b->x[b->dim - 1], b->x[2 * b->dim - 1]) &&
+ !cube_left(a, b) && !cube_right(a, b));
}
/* is the left edge of (a) located to the right of
return (FALSE);
return (min(a->x[a->dim - 1], a->x[2 * a->dim - 1]) >=
- min(b->x[b->dim - 1], b->x[2 * b->dim - 1]) &&
- !cube_left(a, b) && !cube_right(a, b));
+ min(b->x[b->dim - 1], b->x[2 * b->dim - 1]) &&
+ !cube_left(a, b) && !cube_right(a, b));
}
return (FALSE);
return (min(a->x[a->dim - 1], a->x[2 * a->dim - 1]) <
- min(b->x[0], b->x[b->dim]));
+ min(b->x[0], b->x[b->dim]));
}
/* return 'true' if the projection of 'a' is
return (FALSE);
return (min(a->x[0], a->x[a->dim]) >
- min(b->x[b->dim - 1], b->x[2 * b->dim - 1]));
+ min(b->x[b->dim - 1], b->x[2 * b->dim - 1]));
}
/* make up a metric in which one box will be 'lower' than the other
for (i = 0; i < dim; i++)
{
if (min(a->x[i], a->x[a->dim + i]) >
- min(b->x[i], b->x[b->dim + i]))
+ min(b->x[i], b->x[b->dim + i]))
return (FALSE);
if (min(a->x[i], a->x[a->dim + i]) <
- min(b->x[i], b->x[b->dim + i]))
+ min(b->x[i], b->x[b->dim + i]))
return (TRUE);
}
for (i = 0; i < dim; i++)
{
if (max(a->x[i], a->x[a->dim + i]) >
- max(b->x[i], b->x[b->dim + i]))
+ max(b->x[i], b->x[b->dim + i]))
return (FALSE);
if (max(a->x[i], a->x[a->dim + i]) <
- max(b->x[i], b->x[b->dim + i]))
+ max(b->x[i], b->x[b->dim + i]))
return (TRUE);
}
if (max(a->x[i], a->x[a->dim + i]) < 0)
return (TRUE);
}
- /*
- * if all common dimensions are equal, the cube with more
- * dimensions wins
- */
- return (FALSE);
+
+ /*
+ * if all common dimensions are equal, the cube with more
+ * dimensions wins
+ */
+ return (FALSE);
}
if (a->dim < b->dim)
{
if (max(b->x[i], b->x[b->dim + i]) < 0)
return (FALSE);
}
- /*
- * if all common dimensions are equal, the cube with more
- * dimensions wins
- */
- return (TRUE);
+
+ /*
+ * if all common dimensions are equal, the cube with more
+ * dimensions wins
+ */
+ return (TRUE);
}
return (FALSE);
for (i = 0; i < dim; i++)
{
if (min(a->x[i], a->x[a->dim + i]) <
- min(b->x[i], b->x[b->dim + i]))
+ min(b->x[i], b->x[b->dim + i]))
return (FALSE);
if (min(a->x[i], a->x[a->dim + i]) >
- min(b->x[i], b->x[b->dim + i]))
+ min(b->x[i], b->x[b->dim + i]))
return (TRUE);
}
for (i = 0; i < dim; i++)
{
if (max(a->x[i], a->x[a->dim + i]) <
- max(b->x[i], b->x[b->dim + i]))
+ max(b->x[i], b->x[b->dim + i]))
return (FALSE);
if (max(a->x[i], a->x[a->dim + i]) >
- max(b->x[i], b->x[b->dim + i]))
+ max(b->x[i], b->x[b->dim + i]))
return (TRUE);
}
if (max(a->x[i], a->x[a->dim + i]) > 0)
return (TRUE);
}
- /*
- * if all common dimensions are equal, the cube with more
- * dimensions wins
- */
- return (TRUE);
+
+ /*
+ * if all common dimensions are equal, the cube with more
+ * dimensions wins
+ */
+ return (TRUE);
}
if (a->dim < b->dim)
{
if (max(b->x[i], b->x[b->dim + i]) > 0)
return (FALSE);
}
- /*
- * if all common dimensions are equal, the cube with more
- * dimensions wins
- */
- return (FALSE);
+
+ /*
+ * if all common dimensions are equal, the cube with more
+ * dimensions wins
+ */
+ return (FALSE);
}
return (FALSE);
for (i = 0; i < b->dim; i++)
{
if (min(a->x[i], a->x[a->dim + i]) !=
- min(b->x[i], b->x[b->dim + i]))
+ min(b->x[i], b->x[b->dim + i]))
return (FALSE);
if (max(a->x[i], a->x[a->dim + i]) !=
- max(b->x[i], b->x[b->dim + i]))
+ max(b->x[i], b->x[b->dim + i]))
return (FALSE);
}
/*
* all dimensions of (b) are compared to those of (a); instead of
- * those in (a) absent in (b), compare (a) to zero
- * Since both LL and UR coordinates are compared to zero, we can
- * just check them all without worrying about which is which.
+ * those in (a) absent in (b), compare (a) to zero Since both LL and
+ * UR coordinates are compared to zero, we can just check them all
+ * without worrying about which is which.
*/
for (i = b->dim; i < a->dim; i++)
{
{
/*
* the further comparisons will make sense if the excess
- * dimensions of (b) were zeroes
- * Since both UL and UR coordinates must be zero, we can
- * check them all without worrying about which is which.
+ * dimensions of (b) were zeroes Since both UL and UR coordinates
+ * must be zero, we can check them all without worrying about
+ * which is which.
*/
for (i = a->dim; i < b->dim; i++)
{
for (i = 0; i < min(a->dim, b->dim); i++)
{
if (min(a->x[i], a->x[a->dim + i]) >
- min(b->x[i], b->x[b->dim + i]))
+ min(b->x[i], b->x[b->dim + i]))
return (FALSE);
if (max(a->x[i], a->x[a->dim + i]) <
- max(b->x[i], b->x[b->dim + i]))
+ max(b->x[i], b->x[b->dim + i]))
return (FALSE);
}
for (i = 0; i < b->dim; i++)
{
if (min(a->x[i], a->x[a->dim + i]) >
- max(b->x[i], b->x[b->dim + i]))
+ max(b->x[i], b->x[b->dim + i]))
return (FALSE);
if (max(a->x[i], a->x[a->dim + i]) <
- min(b->x[i], b->x[b->dim + i]))
+ min(b->x[i], b->x[b->dim + i]))
return (FALSE);
}
bool
cube_is_point(NDBOX * a)
{
- int i,
- j;
+ int i,
+ j;
+
for (i = 0, j = a->dim; i < a->dim; i++, j++)
- {
- if (a->x[i] != a->x[j]) return FALSE;
- }
+ {
+ if (a->x[i] != a->x[j])
+ return FALSE;
+ }
- return TRUE;
+ return TRUE;
}
/* Return dimensions in use in the data structure */
int
cube_dim(NDBOX * a)
{
- /* Other things will break before unsigned int doesn't fit. */
- return a->dim;
+ /* Other things will break before unsigned int doesn't fit. */
+ return a->dim;
}
/* Return a specific normalized LL coordinate */
double *
cube_ll_coord(NDBOX * a, int n)
{
- double *result;
+ double *result;
+
result = (double *) palloc(sizeof(double));
- *result = 0;
- if (a->dim >= n && n > 0)
- *result = min(a->x[n-1], a->x[a->dim + n-1]);
- return result;
+ *result = 0;
+ if (a->dim >= n && n > 0)
+ *result = min(a->x[n - 1], a->x[a->dim + n - 1]);
+ return result;
}
/* Return a specific normalized UR coordinate */
double *
cube_ur_coord(NDBOX * a, int n)
{
- double *result;
+ double *result;
+
result = (double *) palloc(sizeof(double));
- *result = 0;
- if (a->dim >= n && n > 0)
- *result = max(a->x[n-1], a->x[a->dim + n-1]);
- return result;
+ *result = 0;
+ if (a->dim >= n && n > 0)
+ *result = max(a->x[n - 1], a->x[a->dim + n - 1]);
+ return result;
}
/* Increase or decrease box size by a radius in at least n dimensions. */
NDBOX *
-cube_enlarge(NDBOX * a, double * r, int n)
+cube_enlarge(NDBOX * a, double *r, int n)
{
- NDBOX *result;
- int dim = 0;
- int size;
- int i,
- j;
- if (*r > 0 && n > 0) dim = n;
- if (a->dim > dim) dim = a->dim;
- size = offsetof(NDBOX, x[0]) + sizeof(double) * dim * 2;
- result = (NDBOX *) palloc(size);
- memset(result, 0, size);
- result->size = size;
- result->dim = dim;
+ NDBOX *result;
+ int dim = 0;
+ int size;
+ int i,
+ j;
+
+ if (*r > 0 && n > 0)
+ dim = n;
+ if (a->dim > dim)
+ dim = a->dim;
+ size = offsetof(NDBOX, x[0]) + sizeof(double) * dim * 2;
+ result = (NDBOX *) palloc(size);
+ memset(result, 0, size);
+ result->size = size;
+ result->dim = dim;
for (i = 0, j = dim; i < a->dim; i++, j++)
- {
- if (a->x[i] >= a->x[j])
- {
- result->x[i] = a->x[j] - *r;
- result->x[j] = a->x[i] + *r;
- }
- else
- {
- result->x[i] = a->x[i] - *r;
- result->x[j] = a->x[j] + *r;
- }
- if (result->x[i] > result->x[j])
- {
- result->x[i] = (result->x[i] + result->x[j]) / 2;
- result->x[j] = result->x[i];
- }
- }
- /* dim > a->dim only if r > 0 */
+ {
+ if (a->x[i] >= a->x[j])
+ {
+ result->x[i] = a->x[j] - *r;
+ result->x[j] = a->x[i] + *r;
+ }
+ else
+ {
+ result->x[i] = a->x[i] - *r;
+ result->x[j] = a->x[j] + *r;
+ }
+ if (result->x[i] > result->x[j])
+ {
+ result->x[i] = (result->x[i] + result->x[j]) / 2;
+ result->x[j] = result->x[i];
+ }
+ }
+ /* dim > a->dim only if r > 0 */
for (; i < dim; i++, j++)
- {
- result->x[i] = -*r;
- result->x[j] = *r;
- }
- return result;
+ {
+ result->x[i] = -*r;
+ result->x[j] = *r;
+ }
+ return result;
}
{
strcat(query, " varchar");
snprintf(t, 20, "(%d)",
- dbh->db_fields[i].db_flen);
+ dbh->db_fields[i].db_flen);
strcat(query, t);
}
else
if ((strlen(foo) == 8) && isinteger(foo))
{
snprintf(pgdate, 11, "%c%c%c%c-%c%c-%c%c",
- foo[0], foo[1], foo[2], foo[3],
- foo[4], foo[5], foo[6], foo[7]);
+ foo[0], foo[1], foo[2], foo[3],
+ foo[4], foo[5], foo[6], foo[7]);
strcat(query, pgdate);
}
else
static char *quote_ident_cstr(char *rawstr);
static int16 get_attnum_pk_pos(int16 *pkattnums, int16 pknumatts, int16 key);
static HeapTuple get_tuple_of_interest(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals);
-static Oid get_relid_from_relname(text *relname_text);
+static Oid get_relid_from_relname(text *relname_text);
static dblink_results *get_res_ptr(int32 res_id_index);
-static void append_res_ptr(dblink_results *results);
-static void remove_res_ptr(dblink_results *results);
+static void append_res_ptr(dblink_results * results);
+static void remove_res_ptr(dblink_results * results);
static TupleDesc pgresultGetTupleDesc(PGresult *res);
/* Global */
Datum
dblink_connect(PG_FUNCTION_ARGS)
{
- char *connstr = GET_STR(PG_GETARG_TEXT_P(0));
- char *msg;
- text *result_text;
- MemoryContext oldcontext;
+ char *connstr = GET_STR(PG_GETARG_TEXT_P(0));
+ char *msg;
+ text *result_text;
+ MemoryContext oldcontext;
if (persistent_conn != NULL)
PQfinish(persistent_conn);
Datum
dblink_disconnect(PG_FUNCTION_ARGS)
{
- text *result_text;
+ text *result_text;
if (persistent_conn != NULL)
PQfinish(persistent_conn);
Datum
dblink_open(PG_FUNCTION_ARGS)
{
- char *msg;
- PGresult *res = NULL;
- PGconn *conn = NULL;
- text *result_text;
- char *curname = GET_STR(PG_GETARG_TEXT_P(0));
- char *sql = GET_STR(PG_GETARG_TEXT_P(1));
- StringInfo str = makeStringInfo();
+ char *msg;
+ PGresult *res = NULL;
+ PGconn *conn = NULL;
+ text *result_text;
+ char *curname = GET_STR(PG_GETARG_TEXT_P(0));
+ char *sql = GET_STR(PG_GETARG_TEXT_P(1));
+ StringInfo str = makeStringInfo();
if (persistent_conn != NULL)
conn = persistent_conn;
Datum
dblink_close(PG_FUNCTION_ARGS)
{
- PGconn *conn = NULL;
- PGresult *res = NULL;
- char *curname = GET_STR(PG_GETARG_TEXT_P(0));
- StringInfo str = makeStringInfo();
- text *result_text;
- char *msg;
+ PGconn *conn = NULL;
+ PGresult *res = NULL;
+ char *curname = GET_STR(PG_GETARG_TEXT_P(0));
+ StringInfo str = makeStringInfo();
+ text *result_text;
+ char *msg;
if (persistent_conn != NULL)
conn = persistent_conn;
/* close the cursor */
res = PQexec(conn, str->data);
- if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
+ if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
{
msg = pstrdup(PQerrorMessage(conn));
PQclear(res);
Datum
dblink_fetch(PG_FUNCTION_ARGS)
{
- FuncCallContext *funcctx;
- TupleDesc tupdesc = NULL;
- int call_cntr;
- int max_calls;
- TupleTableSlot *slot;
- AttInMetadata *attinmeta;
- char *msg;
- PGresult *res = NULL;
- MemoryContext oldcontext;
+ FuncCallContext *funcctx;
+ TupleDesc tupdesc = NULL;
+ int call_cntr;
+ int max_calls;
+ TupleTableSlot *slot;
+ AttInMetadata *attinmeta;
+ char *msg;
+ PGresult *res = NULL;
+ MemoryContext oldcontext;
/* stuff done only on the first call of the function */
- if(SRF_IS_FIRSTCALL())
- {
- Oid functypeid;
- char functyptype;
- Oid funcid = fcinfo->flinfo->fn_oid;
- PGconn *conn = NULL;
- StringInfo str = makeStringInfo();
- char *curname = GET_STR(PG_GETARG_TEXT_P(0));
- int howmany = PG_GETARG_INT32(1);
+ if (SRF_IS_FIRSTCALL())
+ {
+ Oid functypeid;
+ char functyptype;
+ Oid funcid = fcinfo->flinfo->fn_oid;
+ PGconn *conn = NULL;
+ StringInfo str = makeStringInfo();
+ char *curname = GET_STR(PG_GETARG_TEXT_P(0));
+ int howmany = PG_GETARG_INT32(1);
/* create a function context for cross-call persistence */
- funcctx = SRF_FIRSTCALL_INIT();
+ funcctx = SRF_FIRSTCALL_INIT();
- /* switch to memory context appropriate for multiple function calls */
+ /*
+ * switch to memory context appropriate for multiple function
+ * calls
+ */
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
if (persistent_conn != NULL)
/* fast track when no results */
if (funcctx->max_calls < 1)
- SRF_RETURN_DONE(funcctx);
+ SRF_RETURN_DONE(funcctx);
/* check typtype to see if we have a predetermined return type */
functypeid = get_func_rettype(funcid);
funcctx->attinmeta = attinmeta;
MemoryContextSwitchTo(oldcontext);
- }
+ }
/* stuff done on every call of the function */
- funcctx = SRF_PERCALL_SETUP();
+ funcctx = SRF_PERCALL_SETUP();
/*
* initialize per-call variables
tupdesc = attinmeta->tupdesc;
if (call_cntr < max_calls) /* do when there is more left to send */
- {
+ {
char **values;
HeapTuple tuple;
Datum result;
- int i;
- int nfields = PQnfields(res);
+ int i;
+ int nfields = PQnfields(res);
values = (char **) palloc(nfields * sizeof(char *));
for (i = 0; i < nfields; i++)
/* make the tuple into a datum */
result = TupleGetDatum(slot, tuple);
- SRF_RETURN_NEXT(funcctx, result);
+ SRF_RETURN_NEXT(funcctx, result);
}
- else /* do when there is no more left */
+ else
+/* do when there is no more left */
{
PQclear(res);
- SRF_RETURN_DONE(funcctx);
+ SRF_RETURN_DONE(funcctx);
}
}
Datum
dblink_record(PG_FUNCTION_ARGS)
{
- FuncCallContext *funcctx;
- TupleDesc tupdesc = NULL;
- int call_cntr;
- int max_calls;
- TupleTableSlot *slot;
- AttInMetadata *attinmeta;
- char *msg;
- PGresult *res = NULL;
- bool is_sql_cmd = false;
- char *sql_cmd_status = NULL;
- MemoryContext oldcontext;
+ FuncCallContext *funcctx;
+ TupleDesc tupdesc = NULL;
+ int call_cntr;
+ int max_calls;
+ TupleTableSlot *slot;
+ AttInMetadata *attinmeta;
+ char *msg;
+ PGresult *res = NULL;
+ bool is_sql_cmd = false;
+ char *sql_cmd_status = NULL;
+ MemoryContext oldcontext;
/* stuff done only on the first call of the function */
- if(SRF_IS_FIRSTCALL())
- {
- Oid functypeid;
- char functyptype;
- Oid funcid = fcinfo->flinfo->fn_oid;
- PGconn *conn = NULL;
- char *connstr = NULL;
- char *sql = NULL;
+ if (SRF_IS_FIRSTCALL())
+ {
+ Oid functypeid;
+ char functyptype;
+ Oid funcid = fcinfo->flinfo->fn_oid;
+ PGconn *conn = NULL;
+ char *connstr = NULL;
+ char *sql = NULL;
/* create a function context for cross-call persistence */
- funcctx = SRF_FIRSTCALL_INIT();
+ funcctx = SRF_FIRSTCALL_INIT();
- /* switch to memory context appropriate for multiple function calls */
+ /*
+ * switch to memory context appropriate for multiple function
+ * calls
+ */
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
if (fcinfo->nargs == 2)
/* fast track when no results */
if (funcctx->max_calls < 1)
- SRF_RETURN_DONE(funcctx);
+ SRF_RETURN_DONE(funcctx);
/* check typtype to see if we have a predetermined return type */
functypeid = get_func_rettype(funcid);
funcctx->attinmeta = attinmeta;
MemoryContextSwitchTo(oldcontext);
- }
+ }
/* stuff done on every call of the function */
- funcctx = SRF_PERCALL_SETUP();
+ funcctx = SRF_PERCALL_SETUP();
/*
* initialize per-call variables
tupdesc = attinmeta->tupdesc;
if (call_cntr < max_calls) /* do when there is more left to send */
- {
+ {
char **values;
HeapTuple tuple;
Datum result;
if (!is_sql_cmd)
{
- int i;
- int nfields = PQnfields(res);
+ int i;
+ int nfields = PQnfields(res);
values = (char **) palloc(nfields * sizeof(char *));
for (i = 0; i < nfields; i++)
/* make the tuple into a datum */
result = TupleGetDatum(slot, tuple);
- SRF_RETURN_NEXT(funcctx, result);
+ SRF_RETURN_NEXT(funcctx, result);
}
- else /* do when there is no more left */
+ else
+/* do when there is no more left */
{
PQclear(res);
- SRF_RETURN_DONE(funcctx);
+ SRF_RETURN_DONE(funcctx);
}
}
Datum
dblink_exec(PG_FUNCTION_ARGS)
{
- char *msg;
- PGresult *res = NULL;
- char *sql_cmd_status = NULL;
- TupleDesc tupdesc = NULL;
- text *result_text;
- PGconn *conn = NULL;
- char *connstr = NULL;
- char *sql = NULL;
+ char *msg;
+ PGresult *res = NULL;
+ char *sql_cmd_status = NULL;
+ TupleDesc tupdesc = NULL;
+ text *result_text;
+ PGconn *conn = NULL;
+ char *connstr = NULL;
+ char *sql = NULL;
if (fcinfo->nargs == 2)
{
TEXTOID, -1, 0, false);
/*
- * and save a copy of the command status string to return
- * as our result tuple
+ * and save a copy of the command status string to return as
+ * our result tuple
*/
sql_cmd_status = PQcmdStatus(res);
}
Datum
dblink(PG_FUNCTION_ARGS)
{
- PGconn *conn = NULL;
- PGresult *res = NULL;
- dblink_results *results;
- char *optstr;
- char *sqlstatement;
- char *execstatement;
- char *msg;
- int ntuples = 0;
- ReturnSetInfo *rsi;
+ PGconn *conn = NULL;
+ PGresult *res = NULL;
+ dblink_results *results;
+ char *optstr;
+ char *sqlstatement;
+ char *execstatement;
+ char *msg;
+ int ntuples = 0;
+ ReturnSetInfo *rsi;
if (fcinfo->resultinfo == NULL || !IsA(fcinfo->resultinfo, ReturnSetInfo))
elog(ERROR, "dblink: function called in context that does not accept a set result");
results->res = res;
/*
- * Append node to res_id to hold pointer to results.
- * Needed by dblink_tok to access the data
+ * Append node to res_id to hold pointer to results. Needed by
+ * dblink_tok to access the data
*/
append_res_ptr(results);
dblink_tok(PG_FUNCTION_ARGS)
{
dblink_results *results;
- int fldnum;
- text *result_text;
- char *result;
- int nfields = 0;
- int text_len = 0;
+ int fldnum;
+ text *result_text;
+ char *result;
+ int nfields = 0;
+ int text_len = 0;
results = get_res_ptr(PG_GETARG_INT32(0));
if (results == NULL)
/*
* dblink_get_pkey
- *
+ *
* Return list of primary key fields for the supplied relation,
* or NULL if none exists.
*/
Datum
dblink_get_pkey(PG_FUNCTION_ARGS)
{
- int16 numatts;
- Oid relid;
- char **results;
- FuncCallContext *funcctx;
- int32 call_cntr;
- int32 max_calls;
- TupleTableSlot *slot;
- AttInMetadata *attinmeta;
- MemoryContext oldcontext;
+ int16 numatts;
+ Oid relid;
+ char **results;
+ FuncCallContext *funcctx;
+ int32 call_cntr;
+ int32 max_calls;
+ TupleTableSlot *slot;
+ AttInMetadata *attinmeta;
+ MemoryContext oldcontext;
/* stuff done only on the first call of the function */
- if(SRF_IS_FIRSTCALL())
- {
- TupleDesc tupdesc = NULL;
+ if (SRF_IS_FIRSTCALL())
+ {
+ TupleDesc tupdesc = NULL;
/* create a function context for cross-call persistence */
- funcctx = SRF_FIRSTCALL_INIT();
+ funcctx = SRF_FIRSTCALL_INIT();
- /* switch to memory context appropriate for multiple function calls */
+ /*
+ * switch to memory context appropriate for multiple function
+ * calls
+ */
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* convert relname to rel Oid */
if (!OidIsValid(relid))
elog(ERROR, "dblink_get_pkey: relation does not exist");
- /* need a tuple descriptor representing one INT and one TEXT column */
+ /*
+ * need a tuple descriptor representing one INT and one TEXT
+ * column
+ */
tupdesc = CreateTemplateTupleDesc(2, false);
TupleDescInitEntry(tupdesc, (AttrNumber) 1, "position",
INT4OID, -1, 0, false);
funcctx->slot = slot;
/*
- * Generate attribute metadata needed later to produce tuples from raw
- * C strings
+ * Generate attribute metadata needed later to produce tuples from
+ * raw C strings
*/
attinmeta = TupleDescGetAttInMetadata(tupdesc);
funcctx->attinmeta = attinmeta;
/* got results, keep track of them */
funcctx->user_fctx = results;
}
- else /* fast track when no results */
- SRF_RETURN_DONE(funcctx);
+ else
+/* fast track when no results */
+ SRF_RETURN_DONE(funcctx);
MemoryContextSwitchTo(oldcontext);
- }
+ }
/* stuff done on every call of the function */
- funcctx = SRF_PERCALL_SETUP();
+ funcctx = SRF_PERCALL_SETUP();
/*
* initialize per-call variables
attinmeta = funcctx->attinmeta;
if (call_cntr < max_calls) /* do when there is more left to send */
- {
+ {
char **values;
HeapTuple tuple;
Datum result;
values = (char **) palloc(2 * sizeof(char *));
- values[0] = (char *) palloc(12); /* sign, 10 digits, '\0' */
+ values[0] = (char *) palloc(12); /* sign, 10 digits, '\0' */
sprintf(values[0], "%d", call_cntr + 1);
/* make the tuple into a datum */
result = TupleGetDatum(slot, tuple);
- SRF_RETURN_NEXT(funcctx, result);
+ SRF_RETURN_NEXT(funcctx, result);
}
- else /* do when there is no more left */
- SRF_RETURN_DONE(funcctx);
+ else
+/* do when there is no more left */
+ SRF_RETURN_DONE(funcctx);
}
/*
/*
* dblink_build_sql_insert
- *
+ *
* Used to generate an SQL insert statement
* based on an existing tuple in a local relation.
* This is useful for selectively replicating data
int *src_dim;
int src_nitems;
int tgt_ndim;
- int *tgt_dim;
+ int *tgt_dim;
int tgt_nitems;
int i;
char *ptr;
pkattnums = (int16 *) PG_GETARG_POINTER(1);
pknumatts = PG_GETARG_INT16(2);
+
/*
* There should be at least one key attribute
*/
tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
/*
- * Source array is made up of key values that will be used to
- * locate the tuple of interest from the local system.
+ * Source array is made up of key values that will be used to locate
+ * the tuple of interest from the local system.
*/
src_ndim = ARR_NDIM(src_pkattvals_arry);
src_dim = ARR_DIMS(src_pkattvals_arry);
*/
Assert(ARR_ELEMTYPE(src_pkattvals_arry) == TEXTOID);
get_typlenbyvalalign(ARR_ELEMTYPE(src_pkattvals_arry),
- &typlen, &typbyval, &typalign);
+ &typlen, &typbyval, &typalign);
src_pkattvals = (char **) palloc(src_nitems * sizeof(char *));
ptr = ARR_DATA_PTR(src_pkattvals_arry);
}
/*
- * Target array is made up of key values that will be used to
- * build the SQL string for use on the remote system.
+ * Target array is made up of key values that will be used to build
+ * the SQL string for use on the remote system.
*/
tgt_ndim = ARR_NDIM(tgt_pkattvals_arry);
tgt_dim = ARR_DIMS(tgt_pkattvals_arry);
*/
Assert(ARR_ELEMTYPE(tgt_pkattvals_arry) == TEXTOID);
get_typlenbyvalalign(ARR_ELEMTYPE(tgt_pkattvals_arry),
- &typlen, &typbyval, &typalign);
+ &typlen, &typbyval, &typalign);
tgt_pkattvals = (char **) palloc(tgt_nitems * sizeof(char *));
ptr = ARR_DATA_PTR(tgt_pkattvals_arry);
/*
* dblink_build_sql_delete
- *
+ *
* Used to generate an SQL delete statement.
* This is useful for selectively replicating a
* delete to another server via dblink.
dblink_build_sql_delete(PG_FUNCTION_ARGS)
{
Oid relid;
- text *relname_text;
- int16 *pkattnums;
+ text *relname_text;
+ int16 *pkattnums;
int16 pknumatts;
- char **tgt_pkattvals;
- ArrayType *tgt_pkattvals_arry;
+ char **tgt_pkattvals;
+ ArrayType *tgt_pkattvals_arry;
int tgt_ndim;
- int *tgt_dim;
+ int *tgt_dim;
int tgt_nitems;
int i;
- char *ptr;
- char *sql;
- text *sql_text;
+ char *ptr;
+ char *sql;
+ text *sql_text;
int16 typlen;
bool typbyval;
char typalign;
pkattnums = (int16 *) PG_GETARG_POINTER(1);
pknumatts = PG_GETARG_INT16(2);
+
/*
* There should be at least one key attribute
*/
tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
/*
- * Target array is made up of key values that will be used to
- * build the SQL string for use on the remote system.
+ * Target array is made up of key values that will be used to build
+ * the SQL string for use on the remote system.
*/
tgt_ndim = ARR_NDIM(tgt_pkattvals_arry);
tgt_dim = ARR_DIMS(tgt_pkattvals_arry);
*/
Assert(ARR_ELEMTYPE(tgt_pkattvals_arry) == TEXTOID);
get_typlenbyvalalign(ARR_ELEMTYPE(tgt_pkattvals_arry),
- &typlen, &typbyval, &typalign);
+ &typlen, &typbyval, &typalign);
tgt_pkattvals = (char **) palloc(tgt_nitems * sizeof(char *));
ptr = ARR_DATA_PTR(tgt_pkattvals_arry);
/*
* dblink_build_sql_update
- *
+ *
* Used to generate an SQL update statement
* based on an existing tuple in a local relation.
* This is useful for selectively replicating data
dblink_build_sql_update(PG_FUNCTION_ARGS)
{
Oid relid;
- text *relname_text;
- int16 *pkattnums;
+ text *relname_text;
+ int16 *pkattnums;
int16 pknumatts;
- char **src_pkattvals;
- char **tgt_pkattvals;
- ArrayType *src_pkattvals_arry;
- ArrayType *tgt_pkattvals_arry;
+ char **src_pkattvals;
+ char **tgt_pkattvals;
+ ArrayType *src_pkattvals_arry;
+ ArrayType *tgt_pkattvals_arry;
int src_ndim;
- int *src_dim;
+ int *src_dim;
int src_nitems;
int tgt_ndim;
- int *tgt_dim;
+ int *tgt_dim;
int tgt_nitems;
int i;
- char *ptr;
- char *sql;
- text *sql_text;
+ char *ptr;
+ char *sql;
+ text *sql_text;
int16 typlen;
bool typbyval;
char typalign;
pkattnums = (int16 *) PG_GETARG_POINTER(1);
pknumatts = PG_GETARG_INT16(2);
+
/*
* There should be one source array key values for each key attnum
*/
tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
/*
- * Source array is made up of key values that will be used to
- * locate the tuple of interest from the local system.
+ * Source array is made up of key values that will be used to locate
+ * the tuple of interest from the local system.
*/
src_ndim = ARR_NDIM(src_pkattvals_arry);
src_dim = ARR_DIMS(src_pkattvals_arry);
*/
Assert(ARR_ELEMTYPE(src_pkattvals_arry) == TEXTOID);
get_typlenbyvalalign(ARR_ELEMTYPE(src_pkattvals_arry),
- &typlen, &typbyval, &typalign);
+ &typlen, &typbyval, &typalign);
src_pkattvals = (char **) palloc(src_nitems * sizeof(char *));
ptr = ARR_DATA_PTR(src_pkattvals_arry);
}
/*
- * Target array is made up of key values that will be used to
- * build the SQL string for use on the remote system.
+ * Target array is made up of key values that will be used to build
+ * the SQL string for use on the remote system.
*/
tgt_ndim = ARR_NDIM(tgt_pkattvals_arry);
tgt_dim = ARR_DIMS(tgt_pkattvals_arry);
*/
Assert(ARR_ELEMTYPE(tgt_pkattvals_arry) == TEXTOID);
get_typlenbyvalalign(ARR_ELEMTYPE(tgt_pkattvals_arry),
- &typlen, &typbyval, &typalign);
+ &typlen, &typbyval, &typalign);
tgt_pkattvals = (char **) palloc(tgt_nitems * sizeof(char *));
ptr = ARR_DATA_PTR(tgt_pkattvals_arry);
Datum
dblink_current_query(PG_FUNCTION_ARGS)
{
- text *result_text;
+ text *result_text;
result_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(debug_query_string)));
PG_RETURN_TEXT_P(result_text);
MemSet(retval, 0, sizeof(dblink_results));
retval->tup_num = -1;
- retval->res_id_index =-1;
+ retval->res_id_index = -1;
retval->res = NULL;
MemoryContextSwitchTo(oldcontext);
/*
* get_pkey_attnames
- *
+ *
* Get the primary key attnames for the given relation.
* Return NULL, and set numatts = 0, if no primary key exists.
*/
static char **
get_pkey_attnames(Oid relid, int16 *numatts)
{
- Relation indexRelation;
- ScanKeyData entry;
- HeapScanDesc scan;
- HeapTuple indexTuple;
- int i;
- char **result = NULL;
- Relation rel;
- TupleDesc tupdesc;
+ Relation indexRelation;
+ ScanKeyData entry;
+ HeapScanDesc scan;
+ HeapTuple indexTuple;
+ int i;
+ char **result = NULL;
+ Relation rel;
+ TupleDesc tupdesc;
/* open relation using relid, get tupdesc */
rel = relation_open(relid, AccessShareLock);
while ((indexTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
- Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
+ Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
/* we're only interested if it is the primary key */
if (index->indisprimary == TRUE)
static char *
get_sql_insert(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals, char **tgt_pkattvals)
{
- Relation rel;
- char *relname;
- HeapTuple tuple;
- TupleDesc tupdesc;
- int natts;
- StringInfo str = makeStringInfo();
- char *sql;
- char *val;
- int16 key;
- int i;
- bool needComma;
+ Relation rel;
+ char *relname;
+ HeapTuple tuple;
+ TupleDesc tupdesc;
+ int natts;
+ StringInfo str = makeStringInfo();
+ char *sql;
+ char *val;
+ int16 key;
+ int i;
+ bool needComma;
/*
* Open relation using relid
*/
rel = relation_open(relid, AccessShareLock);
- relname = RelationGetRelationName(rel);
+ relname = RelationGetRelationName(rel);
tupdesc = rel->rd_att;
natts = tupdesc->natts;
appendStringInfo(str, ",");
appendStringInfo(str, "%s",
- quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
+ quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
needComma = true;
}
static char *
get_sql_delete(Oid relid, int16 *pkattnums, int16 pknumatts, char **tgt_pkattvals)
{
- Relation rel;
- char *relname;
- TupleDesc tupdesc;
- int natts;
- StringInfo str = makeStringInfo();
- char *sql;
- char *val;
- int i;
+ Relation rel;
+ char *relname;
+ TupleDesc tupdesc;
+ int natts;
+ StringInfo str = makeStringInfo();
+ char *sql;
+ char *val;
+ int i;
/*
* Open relation using relid
*/
rel = relation_open(relid, AccessShareLock);
- relname = RelationGetRelationName(rel);
+ relname = RelationGetRelationName(rel);
tupdesc = rel->rd_att;
natts = tupdesc->natts;
appendStringInfo(str, "DELETE FROM %s WHERE ", quote_ident_cstr(relname));
for (i = 0; i < pknumatts; i++)
{
- int16 pkattnum = pkattnums[i];
+ int16 pkattnum = pkattnums[i];
if (i > 0)
appendStringInfo(str, " AND ");
appendStringInfo(str, "%s",
- quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
+ quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
if (tgt_pkattvals != NULL)
val = pstrdup(tgt_pkattvals[i]);
static char *
get_sql_update(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals, char **tgt_pkattvals)
{
- Relation rel;
- char *relname;
- HeapTuple tuple;
- TupleDesc tupdesc;
- int natts;
- StringInfo str = makeStringInfo();
- char *sql;
- char *val;
- int16 key;
- int i;
- bool needComma;
+ Relation rel;
+ char *relname;
+ HeapTuple tuple;
+ TupleDesc tupdesc;
+ int natts;
+ StringInfo str = makeStringInfo();
+ char *sql;
+ char *val;
+ int16 key;
+ int i;
+ bool needComma;
/*
* Open relation using relid
*/
rel = relation_open(relid, AccessShareLock);
- relname = RelationGetRelationName(rel);
+ relname = RelationGetRelationName(rel);
tupdesc = rel->rd_att;
natts = tupdesc->natts;
appendStringInfo(str, ", ");
appendStringInfo(str, "%s = ",
- quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
+ quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
if (tgt_pkattvals != NULL)
key = get_attnum_pk_pos(pkattnums, pknumatts, i + 1);
for (i = 0; i < pknumatts; i++)
{
- int16 pkattnum = pkattnums[i];
+ int16 pkattnum = pkattnums[i];
if (i > 0)
appendStringInfo(str, " AND ");
appendStringInfo(str, "%s",
- quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
+ quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
if (tgt_pkattvals != NULL)
val = pstrdup(tgt_pkattvals[i]);
static char *
quote_literal_cstr(char *rawstr)
{
- text *rawstr_text;
- text *result_text;
- char *result;
+ text *rawstr_text;
+ text *result_text;
+ char *result;
rawstr_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(rawstr)));
result_text = DatumGetTextP(DirectFunctionCall1(quote_literal, PointerGetDatum(rawstr_text)));
static char *
quote_ident_cstr(char *rawstr)
{
- text *rawstr_text;
- text *result_text;
- char *result;
+ text *rawstr_text;
+ text *result_text;
+ char *result;
rawstr_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(rawstr)));
result_text = DatumGetTextP(DirectFunctionCall1(quote_ident, PointerGetDatum(rawstr_text)));
static int16
get_attnum_pk_pos(int16 *pkattnums, int16 pknumatts, int16 key)
{
- int i;
+ int i;
/*
- * Not likely a long list anyway, so just scan for
- * the value
+ * Not likely a long list anyway, so just scan for the value
*/
for (i = 0; i < pknumatts; i++)
if (key == pkattnums[i])
static HeapTuple
get_tuple_of_interest(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals)
{
- Relation rel;
- char *relname;
- TupleDesc tupdesc;
- StringInfo str = makeStringInfo();
- char *sql = NULL;
- int ret;
- HeapTuple tuple;
- int i;
- char *val = NULL;
+ Relation rel;
+ char *relname;
+ TupleDesc tupdesc;
+ StringInfo str = makeStringInfo();
+ char *sql = NULL;
+ int ret;
+ HeapTuple tuple;
+ int i;
+ char *val = NULL;
/*
* Open relation using relid
*/
rel = relation_open(relid, AccessShareLock);
- relname = RelationGetRelationName(rel);
+ relname = RelationGetRelationName(rel);
tupdesc = CreateTupleDescCopy(rel->rd_att);
relation_close(rel, AccessShareLock);
elog(ERROR, "get_tuple_of_interest: SPI_connect returned %d", ret);
/*
- * Build sql statement to look up tuple of interest
- * Use src_pkattvals as the criteria.
+ * Build sql statement to look up tuple of interest Use src_pkattvals
+ * as the criteria.
*/
appendStringInfo(str, "SELECT * FROM %s WHERE ", quote_ident_cstr(relname));
for (i = 0; i < pknumatts; i++)
{
- int16 pkattnum = pkattnums[i];
+ int16 pkattnum = pkattnums[i];
if (i > 0)
appendStringInfo(str, " AND ");
appendStringInfo(str, "%s",
- quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
+ quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
val = pstrdup(src_pkattvals[i]);
if (val != NULL)
sql = pstrdup(str->data);
pfree(str->data);
pfree(str);
+
/*
* Retrieve the desired tuple
*/
* Only allow one qualifying tuple
*/
if ((ret == SPI_OK_SELECT) && (SPI_processed > 1))
- {
elog(ERROR, "get_tuple_of_interest: Source criteria may not match more than one record.");
- }
else if (ret == SPI_OK_SELECT && SPI_processed == 1)
{
SPITupleTable *tuptable = SPI_tuptable;
+
tuple = SPI_copytuple(tuptable->vals[0]);
return tuple;
return relid;
}
-static dblink_results *
+static dblink_results *
get_res_ptr(int32 res_id_index)
{
- List *ptr;
+ List *ptr;
/*
* short circuit empty list
*/
- if(res_id == NIL)
+ if (res_id == NIL)
return NULL;
/*
*/
foreach(ptr, res_id)
{
- dblink_results *this_res_id = (dblink_results *) lfirst(ptr);
+ dblink_results *this_res_id = (dblink_results *) lfirst(ptr);
+
if (this_res_id->res_id_index == res_id_index)
return this_res_id;
}
* Add node to global List res_id
*/
static void
-append_res_ptr(dblink_results *results)
+append_res_ptr(dblink_results * results)
{
res_id = lappend(res_id, results);
}
* using res_id_index
*/
static void
-remove_res_ptr(dblink_results *results)
+remove_res_ptr(dblink_results * results)
{
res_id = lremove(results, res_id);
static TupleDesc
pgresultGetTupleDesc(PGresult *res)
{
- int natts;
- AttrNumber attnum;
- TupleDesc desc;
- char *attname;
- int32 atttypmod;
- int attdim;
- bool attisset;
- Oid atttypid;
- int i;
+ int natts;
+ AttrNumber attnum;
+ TupleDesc desc;
+ char *attname;
+ int32 atttypmod;
+ int attdim;
+ bool attisset;
+ Oid atttypid;
+ int i;
/*
* allocate a new tuple descriptor
for (i = 0; i < natts; i++)
{
/*
- * for each field, get the name and type information from the query
- * result and have TupleDescInitEntry fill in the attribute
+ * for each field, get the name and type information from the
+ * query result and have TupleDescInitEntry fill in the attribute
* information we need.
*/
attnum++;
if (PQfsize(res, i) != get_typlen(atttypid))
elog(ERROR, "Size of remote field \"%s\" does not match size "
- "of local type \"%s\"",
- attname,
- format_type_with_typemod(atttypid, atttypmod));
+ "of local type \"%s\"",
+ attname,
+ format_type_with_typemod(atttypid, atttypmod));
attdim = 0;
attisset = false;
extern Datum dblink_build_sql_update(PG_FUNCTION_ARGS);
extern Datum dblink_current_query(PG_FUNCTION_ARGS);
-extern char *debug_query_string;
+extern char *debug_query_string;
#endif /* DBLINK_H */
/****************************************************************************
* pending.c
- * $Id: pending.c,v 1.1 2002/06/23 21:58:08 momjian Exp $
+ * $Id: pending.c,v 1.2 2002/09/04 20:31:06 momjian Exp $
*
* This file contains a trigger for Postgresql-7.x to record changes to tables
* to a pending table for mirroring.
* All tables that should be mirrored should have this trigger hooked up to it.
*
- * Written by Steven Singer (ssinger@navtechinc.com)
- * (c) 2001-2002 Navtech Systems Support Inc.
- * Released under the GNU Public License version 2. See COPYING.
+ * Written by Steven Singer (ssinger@navtechinc.com)
+ * (c) 2001-2002 Navtech Systems Support Inc.
+ * Released under the GNU Public License version 2. See COPYING.
*
*
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
*
*
***************************************************************************/
#include <commands/trigger.h>
#include <postgres.h>
-enum FieldUsage {PRIMARY=0,NONPRIMARY,ALL,NUM_FIELDUSAGE};
+enum FieldUsage
+{
+ PRIMARY = 0, NONPRIMARY, ALL, NUM_FIELDUSAGE
+};
-int storePending(char * cpTableName, HeapTuple tBeforeTuple,
- HeapTuple tAfterTuple,
- TupleDesc tTupdesc,
- TriggerData * tpTrigdata,char cOp);
+int storePending(char *cpTableName, HeapTuple tBeforeTuple,
+ HeapTuple tAfterTuple,
+ TupleDesc tTupdesc,
+ TriggerData *tpTrigdata, char cOp);
-int storeKeyInfo(char * cpTableName, HeapTuple tTupleData, TupleDesc tTuplDesc,
- TriggerData * tpTrigdata);
-int storeData(char * cpTableName,HeapTuple tTupleData,TupleDesc tTupleDesc,
- TriggerData * tpTrigData,int iIncludeKeyData);
-
-int2vector * getPrimaryKey(Oid tblOid);
+int storeKeyInfo(char *cpTableName, HeapTuple tTupleData, TupleDesc tTuplDesc,
+ TriggerData *tpTrigdata);
+int storeData(char *cpTableName, HeapTuple tTupleData, TupleDesc tTupleDesc,
+ TriggerData *tpTrigData, int iIncludeKeyData);
-char * packageData(HeapTuple tTupleData, TupleDesc tTupleDecs,
- TriggerData * tTrigData,
- enum FieldUsage eKeyUsage );
+int2vector *getPrimaryKey(Oid tblOid);
+
+char *packageData(HeapTuple tTupleData, TupleDesc tTupleDecs,
+ TriggerData *tTrigData,
+ enum FieldUsage eKeyUsage);
#define BUFFER_SIZE 256
#define MAX_OID_LEN 10
extern Datum recordchange(PG_FUNCTION_ARGS);
+
PG_FUNCTION_INFO_V1(recordchange);
* table the trigger was applied to. If this name is incorrect so will the
* mirroring.
****************************************************************************/
-Datum recordchange(PG_FUNCTION_ARGS) {
- TriggerData * trigdata;
- TupleDesc tupdesc;
- HeapTuple beforeTuple=NULL;
- HeapTuple afterTuple=NULL;
- HeapTuple retTuple=NULL;
- char * tblname;
- char op;
- if(fcinfo->context!=NULL) {
-
- if(SPI_connect() < 0) {
- elog(NOTICE,"storePending could not connect to SPI");
- return -1;
- }
- trigdata = (TriggerData*)fcinfo->context;
- /* Extract the table name */
- tblname = SPI_getrelname(trigdata->tg_relation);
- tupdesc = trigdata->tg_relation->rd_att;
- if(TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event)) {
- retTuple = trigdata->tg_newtuple;
- beforeTuple = trigdata->tg_trigtuple;
- afterTuple = trigdata->tg_newtuple;
- op='u';
-
- }
- else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event)) {
- retTuple = trigdata->tg_trigtuple;
- afterTuple = trigdata->tg_trigtuple;
- op = 'i';
- }
- else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event)) {
- retTuple = trigdata->tg_trigtuple;
- beforeTuple = trigdata->tg_trigtuple;
- op = 'd';
- }
-
- if(storePending(tblname,beforeTuple,afterTuple,tupdesc,trigdata,op)) {
- /* An error occoured. Skip the operation. */
- elog(ERROR,"Operation could not be mirrored");
- return PointerGetDatum(NULL);
-
- }
+Datum
+recordchange(PG_FUNCTION_ARGS)
+{
+ TriggerData *trigdata;
+ TupleDesc tupdesc;
+ HeapTuple beforeTuple = NULL;
+ HeapTuple afterTuple = NULL;
+ HeapTuple retTuple = NULL;
+ char *tblname;
+ char op;
+
+ if (fcinfo->context != NULL)
+ {
+
+ if (SPI_connect() < 0)
+ {
+ elog(NOTICE, "storePending could not connect to SPI");
+ return -1;
+ }
+ trigdata = (TriggerData *) fcinfo->context;
+ /* Extract the table name */
+ tblname = SPI_getrelname(trigdata->tg_relation);
+ tupdesc = trigdata->tg_relation->rd_att;
+ if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
+ {
+ retTuple = trigdata->tg_newtuple;
+ beforeTuple = trigdata->tg_trigtuple;
+ afterTuple = trigdata->tg_newtuple;
+ op = 'u';
+
+ }
+ else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
+ {
+ retTuple = trigdata->tg_trigtuple;
+ afterTuple = trigdata->tg_trigtuple;
+ op = 'i';
+ }
+ else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
+ {
+ retTuple = trigdata->tg_trigtuple;
+ beforeTuple = trigdata->tg_trigtuple;
+ op = 'd';
+ }
+
+ if (storePending(tblname, beforeTuple, afterTuple, tupdesc, trigdata, op))
+ {
+ /* An error occoured. Skip the operation. */
+ elog(ERROR, "Operation could not be mirrored");
+ return PointerGetDatum(NULL);
+
+ }
#if defined DEBUG_OUTPUT
- elog(NOTICE,"Returning on success");
+ elog(NOTICE, "Returning on success");
#endif
- SPI_finish();
- return PointerGetDatum(retTuple);
- }
- else {
- /*
- * Not being called as a trigger.
- */
- return PointerGetDatum(NULL);
- }
+ SPI_finish();
+ return PointerGetDatum(retTuple);
+ }
+ else
+ {
+ /*
+ * Not being called as a trigger.
+ */
+ return PointerGetDatum(NULL);
+ }
}
/*****************************************************************************
* Constructs and executes an SQL query to write a record of this tuple change
- * to the pending table.
+ * to the pending table.
*****************************************************************************/
-int storePending(char * cpTableName, HeapTuple tBeforeTuple,
- HeapTuple tAfterTuple,
- TupleDesc tTupDesc,
- TriggerData * tpTrigData,char cOp) {
- char * cpQueryBase = "INSERT INTO \"Pending\" (\"TableName\",\"Op\",\"XID\") VALUES ($1,$2,$3)";
-
- int iResult=0;
- HeapTuple tCurTuple; // Points the current tuple(before or after)
- Datum saPlanData[4];
- Oid taPlanArgTypes[3] = {NAMEOID,CHAROID,INT4OID};
- void * vpPlan;
-
- tCurTuple = tBeforeTuple ? tBeforeTuple : tAfterTuple;
-
-
-
-
- vpPlan = SPI_prepare(cpQueryBase,3,taPlanArgTypes);
- if(vpPlan==NULL) {
- elog(NOTICE,"Error creating plan");
- }
- // SPI_saveplan(vpPlan);
-
- saPlanData[0] = PointerGetDatum(cpTableName);
- saPlanData[1] = CharGetDatum(cOp);
- saPlanData[2] = Int32GetDatum(GetCurrentTransactionId());
-
-
- iResult = SPI_execp(vpPlan,saPlanData,NULL,1);
- if(iResult < 0) {
- elog(NOTICE,"storedPending fired (%s) returned %d",cpQueryBase,iResult);
- }
-
+int
+storePending(char *cpTableName, HeapTuple tBeforeTuple,
+ HeapTuple tAfterTuple,
+ TupleDesc tTupDesc,
+ TriggerData *tpTrigData, char cOp)
+{
+ char *cpQueryBase = "INSERT INTO \"Pending\" (\"TableName\",\"Op\",\"XID\") VALUES ($1,$2,$3)";
+
+ int iResult = 0;
+ HeapTuple tCurTuple;
+
+ //Points the current tuple(before or after)
+ Datum saPlanData[4];
+ Oid taPlanArgTypes[3] = {NAMEOID, CHAROID, INT4OID};
+ void *vpPlan;
+
+ tCurTuple = tBeforeTuple ? tBeforeTuple : tAfterTuple;
+
+
+
+
+ vpPlan = SPI_prepare(cpQueryBase, 3, taPlanArgTypes);
+ if (vpPlan == NULL)
+ elog(NOTICE, "Error creating plan");
+ /* SPI_saveplan(vpPlan); */
+
+ saPlanData[0] = PointerGetDatum(cpTableName);
+ saPlanData[1] = CharGetDatum(cOp);
+ saPlanData[2] = Int32GetDatum(GetCurrentTransactionId());
+
+
+ iResult = SPI_execp(vpPlan, saPlanData, NULL, 1);
+ if (iResult < 0)
+ elog(NOTICE, "storedPending fired (%s) returned %d", cpQueryBase, iResult);
+
#if defined DEBUG_OUTPUT
- elog(NOTICE,"row successfully stored in pending table");
+ elog(NOTICE, "row successfully stored in pending table");
#endif
- if(cOp=='d') {
- /**
- * This is a record of a delete operation.
- * Just store the key data.
- */
- iResult = storeKeyInfo(cpTableName,tBeforeTuple,tTupDesc,tpTrigData);
- }
- else if (cOp=='i') {
- /**
- * An Insert operation.
- * Store all data
- */
- iResult = storeData(cpTableName,tAfterTuple,tTupDesc,tpTrigData,TRUE);
-
- }
- else {
- /* op must be an update. */
- iResult = storeKeyInfo(cpTableName,tBeforeTuple,tTupDesc,tpTrigData);
- iResult = iResult ? iResult : storeData(cpTableName,tAfterTuple,tTupDesc,
- tpTrigData,TRUE);
- }
+ if (cOp == 'd')
+ {
+ /**
+ * This is a record of a delete operation.
+ * Just store the key data.
+ */
+ iResult = storeKeyInfo(cpTableName, tBeforeTuple, tTupDesc, tpTrigData);
+ }
+ else if (cOp == 'i')
+ {
+ /**
+ * An Insert operation.
+ * Store all data
+ */
+ iResult = storeData(cpTableName, tAfterTuple, tTupDesc, tpTrigData, TRUE);
+
+ }
+ else
+ {
+ /* op must be an update. */
+ iResult = storeKeyInfo(cpTableName, tBeforeTuple, tTupDesc, tpTrigData);
+ iResult = iResult ? iResult : storeData(cpTableName, tAfterTuple, tTupDesc,
+ tpTrigData, TRUE);
+ }
#if defined DEBUG_OUTPUT
- elog(NOTICE,"DOne storing keyinfo");
+ elog(NOTICE, "DOne storing keyinfo");
#endif
-
- return iResult;
+
+ return iResult;
}
-int storeKeyInfo(char * cpTableName, HeapTuple tTupleData,
- TupleDesc tTupleDesc,
- TriggerData * tpTrigData) {
-
- Oid saPlanArgTypes[1] = {NAMEOID};
- char * insQuery = "INSERT INTO \"PendingData\" (\"SeqId\",\"IsKey\",\"Data\") VALUES(currval('\"Pending_SeqId_seq\"'),'t',$1)";
- void * pplan;
- Datum saPlanData[1];
- char * cpKeyData;
- int iRetCode;
-
- pplan = SPI_prepare(insQuery,1,saPlanArgTypes);
- if(pplan==NULL) {
- elog(NOTICE,"Could not prepare INSERT plan");
- return -1;
- }
-
- // pplan = SPI_saveplan(pplan);
- cpKeyData = packageData(tTupleData, tTupleDesc,tpTrigData,PRIMARY);
+int
+storeKeyInfo(char *cpTableName, HeapTuple tTupleData,
+ TupleDesc tTupleDesc,
+ TriggerData *tpTrigData)
+{
+
+ Oid saPlanArgTypes[1] = {NAMEOID};
+ char *insQuery = "INSERT INTO \"PendingData\" (\"SeqId\",\"IsKey\",\"Data\") VALUES(currval('\"Pending_SeqId_seq\"'),'t',$1)";
+ void *pplan;
+ Datum saPlanData[1];
+ char *cpKeyData;
+ int iRetCode;
+
+ pplan = SPI_prepare(insQuery, 1, saPlanArgTypes);
+ if (pplan == NULL)
+ {
+ elog(NOTICE, "Could not prepare INSERT plan");
+ return -1;
+ }
+
+ /* pplan = SPI_saveplan(pplan); */
+ cpKeyData = packageData(tTupleData, tTupleDesc, tpTrigData, PRIMARY);
#if defined DEBUG_OUTPUT
- elog(NOTICE,cpKeyData);
+ elog(NOTICE, cpKeyData);
#endif
- saPlanData[0] = PointerGetDatum(cpKeyData);
-
- iRetCode = SPI_execp(pplan,saPlanData,NULL,1);
-
- if(cpKeyData!=NULL) {
- SPI_pfree(cpKeyData);
- }
-
- if(iRetCode != SPI_OK_INSERT ) {
- elog(NOTICE,"Error inserting row in pendingDelete");
- return -1;
- }
+ saPlanData[0] = PointerGetDatum(cpKeyData);
+
+ iRetCode = SPI_execp(pplan, saPlanData, NULL, 1);
+
+ if (cpKeyData != NULL)
+ SPI_pfree(cpKeyData);
+
+ if (iRetCode != SPI_OK_INSERT)
+ {
+ elog(NOTICE, "Error inserting row in pendingDelete");
+ return -1;
+ }
#if defined DEBUG_OUTPUT
- elog(NOTICE,"INSERT SUCCESFULL");
+ elog(NOTICE, "INSERT SUCCESFULL");
#endif
- return 0;
-
+ return 0;
+
}
-int2vector * getPrimaryKey(Oid tblOid) {
- char * queryBase;
- char * query;
- bool isNull;
- int2vector * resultKey;
- int2vector * tpResultKey;
- HeapTuple resTuple;
- Datum resDatum;
- int ret;
- queryBase = "SELECT indkey FROM pg_index WHERE indisprimary='t' AND indrelid=";
- query = SPI_palloc(strlen(queryBase) + MAX_OID_LEN+1);
- sprintf(query,"%s%d",queryBase,tblOid);
- ret = SPI_exec(query,1);
- if(ret != SPI_OK_SELECT || SPI_processed != 1 ) {
- elog(NOTICE,"Could not select primary index key");
- return NULL;
- }
+int2vector *
+getPrimaryKey(Oid tblOid)
+{
+ char *queryBase;
+ char *query;
+ bool isNull;
+ int2vector *resultKey;
+ int2vector *tpResultKey;
+ HeapTuple resTuple;
+ Datum resDatum;
+ int ret;
+
+ queryBase = "SELECT indkey FROM pg_index WHERE indisprimary='t' AND indrelid=";
+ query = SPI_palloc(strlen(queryBase) + MAX_OID_LEN + 1);
+ sprintf(query, "%s%d", queryBase, tblOid);
+ ret = SPI_exec(query, 1);
+ if (ret != SPI_OK_SELECT || SPI_processed != 1)
+ {
+ elog(NOTICE, "Could not select primary index key");
+ return NULL;
+ }
- resTuple = SPI_tuptable->vals[0];
- resDatum = SPI_getbinval(resTuple,SPI_tuptable->tupdesc,1,&isNull);
+ resTuple = SPI_tuptable->vals[0];
+ resDatum = SPI_getbinval(resTuple, SPI_tuptable->tupdesc, 1, &isNull);
- tpResultKey = (int2vector*) DatumGetPointer(resDatum);
- resultKey = SPI_palloc(sizeof(int2vector));
- memcpy(resultKey,tpResultKey,sizeof(int2vector));
+ tpResultKey = (int2vector *) DatumGetPointer(resDatum);
+ resultKey = SPI_palloc(sizeof(int2vector));
+ memcpy(resultKey, tpResultKey, sizeof(int2vector));
- SPI_pfree(query);
- return resultKey;
+ SPI_pfree(query);
+ return resultKey;
}
/******************************************************************************
* Stores a copy of the non-key data for the row.
*****************************************************************************/
-int storeData(char * cpTableName,HeapTuple tTupleData,TupleDesc tTupleDesc,
- TriggerData * tpTrigData,int iIncludeKeyData) {
-
- Oid planArgTypes[1] = {NAMEOID};
- char * insQuery = "INSERT INTO \"PendingData\" (\"SeqId\",\"IsKey\",\"Data\") VALUES(currval('\"Pending_SeqId_seq\"'),'f',$1)";
- void * pplan;
- Datum planData[1];
- char * cpKeyData;
- int iRetValue;
-
- pplan = SPI_prepare(insQuery,1,planArgTypes);
- if(pplan==NULL) {
- elog(NOTICE,"Could not prepare INSERT plan");
- return -1;
- }
-
- // pplan = SPI_saveplan(pplan);
- if(iIncludeKeyData==0) {
- cpKeyData = packageData(tTupleData, tTupleDesc,tpTrigData,NONPRIMARY);
- }
- else {
- cpKeyData = packageData(tTupleData,tTupleDesc,tpTrigData,ALL);
- }
-
- planData[0] = PointerGetDatum(cpKeyData);
- iRetValue = SPI_execp(pplan,planData,NULL,1);
-
- if(cpKeyData!=0) {
- SPI_pfree(cpKeyData);
- }
-
- if(iRetValue != SPI_OK_INSERT ) {
- elog(NOTICE,"Error inserting row in pendingDelete");
- return -1;
- }
+int
+storeData(char *cpTableName, HeapTuple tTupleData, TupleDesc tTupleDesc,
+ TriggerData *tpTrigData, int iIncludeKeyData)
+{
+
+ Oid planArgTypes[1] = {NAMEOID};
+ char *insQuery = "INSERT INTO \"PendingData\" (\"SeqId\",\"IsKey\",\"Data\") VALUES(currval('\"Pending_SeqId_seq\"'),'f',$1)";
+ void *pplan;
+ Datum planData[1];
+ char *cpKeyData;
+ int iRetValue;
+
+ pplan = SPI_prepare(insQuery, 1, planArgTypes);
+ if (pplan == NULL)
+ {
+ elog(NOTICE, "Could not prepare INSERT plan");
+ return -1;
+ }
+
+ /* pplan = SPI_saveplan(pplan); */
+ if (iIncludeKeyData == 0)
+ cpKeyData = packageData(tTupleData, tTupleDesc, tpTrigData, NONPRIMARY);
+ else
+ cpKeyData = packageData(tTupleData, tTupleDesc, tpTrigData, ALL);
+
+ planData[0] = PointerGetDatum(cpKeyData);
+ iRetValue = SPI_execp(pplan, planData, NULL, 1);
+
+ if (cpKeyData != 0)
+ SPI_pfree(cpKeyData);
+
+ if (iRetValue != SPI_OK_INSERT)
+ {
+ elog(NOTICE, "Error inserting row in pendingDelete");
+ return -1;
+ }
#if defined DEBUG_OUTPUT
- elog(NOTICE,"INSERT SUCCESFULL");
+ elog(NOTICE, "INSERT SUCCESFULL");
#endif
- return 0;
-
+ return 0;
+
}
/**
- * Packages the data in tTupleData into a string of the format
+ * Packages the data in tTupleData into a string of the format
* FieldName='value text' where any quotes inside of value text
* are escaped with a backslash and any backslashes in value text
* are esacped by a second back slash.
*
- * tTupleDesc should be a description of the tuple stored in
- * tTupleData.
+ * tTupleDesc should be a description of the tuple stored in
+ * tTupleData.
*
* eFieldUsage specifies which fields to use.
- * PRIMARY implies include only primary key fields.
- * NONPRIMARY implies include only non-primary key fields.
- * ALL implies include all fields.
+ * PRIMARY implies include only primary key fields.
+ * NONPRIMARY implies include only non-primary key fields.
+ * ALL implies include all fields.
*/
-char * packageData(HeapTuple tTupleData, TupleDesc tTupleDesc,
- TriggerData * tpTrigData,
- enum FieldUsage eKeyUsage ) {
- int iNumCols;
- int2vector * tpPKeys=NULL;
- int iColumnCounter;
- char * cpDataBlock;
- int iDataBlockSize;
- int iUsedDataBlock;
-
- iNumCols = tTupleDesc->natts;
-
- if(eKeyUsage!=ALL) {
- tpPKeys = getPrimaryKey(tpTrigData->tg_relation->rd_id);
- if(tpPKeys==NULL) {
- return NULL;
- }
- }
-#if defined DEBUG_OUTPUT
- if(tpPKeys!=NULL) {
- elog(NOTICE,"Have primary keys");
- }
-#endif
- cpDataBlock = SPI_palloc(BUFFER_SIZE);
- iDataBlockSize = BUFFER_SIZE;
- iUsedDataBlock = 0; /* To account for the null */
-
- for(iColumnCounter=1; iColumnCounter <=iNumCols; iColumnCounter++) {
- int iIsPrimaryKey;
- int iPrimaryKeyIndex;
- char * cpUnFormatedPtr;
- char * cpFormatedPtr;
-
- char * cpFieldName;
- char * cpFieldData;
- if(eKeyUsage!=ALL) {
- //Determine if this is a primary key or not.
- iIsPrimaryKey=0;
- for(iPrimaryKeyIndex=0; (*tpPKeys)[iPrimaryKeyIndex]!=0;
- iPrimaryKeyIndex++) {
- if((*tpPKeys)[iPrimaryKeyIndex]==iColumnCounter) {
- iIsPrimaryKey=1;
- break;
+char *
+packageData(HeapTuple tTupleData, TupleDesc tTupleDesc,
+ TriggerData *tpTrigData,
+ enum FieldUsage eKeyUsage)
+{
+ int iNumCols;
+ int2vector *tpPKeys = NULL;
+ int iColumnCounter;
+ char *cpDataBlock;
+ int iDataBlockSize;
+ int iUsedDataBlock;
+
+ iNumCols = tTupleDesc->natts;
+
+ if (eKeyUsage != ALL)
+ {
+ tpPKeys = getPrimaryKey(tpTrigData->tg_relation->rd_id);
+ if (tpPKeys == NULL)
+ return NULL;
}
- }
- if( iIsPrimaryKey ? (eKeyUsage!=PRIMARY) : (eKeyUsage!=NONPRIMARY)) {
- /**
- * Don't use.
- */
#if defined DEBUG_OUTPUT
- elog(NOTICE,"Skipping column");
+ if (tpPKeys != NULL)
+ elog(NOTICE, "Have primary keys");
#endif
- continue;
- }
- } /* KeyUsage!=ALL */
- cpFieldName = DatumGetPointer(NameGetDatum(&tTupleDesc->attrs
- [iColumnCounter-1]->attname));
+ cpDataBlock = SPI_palloc(BUFFER_SIZE);
+ iDataBlockSize = BUFFER_SIZE;
+ iUsedDataBlock = 0; /* To account for the null */
+
+ for (iColumnCounter = 1; iColumnCounter <= iNumCols; iColumnCounter++)
+ {
+ int iIsPrimaryKey;
+ int iPrimaryKeyIndex;
+ char *cpUnFormatedPtr;
+ char *cpFormatedPtr;
+
+ char *cpFieldName;
+ char *cpFieldData;
+
+ if (eKeyUsage != ALL)
+ {
+ /* Determine if this is a primary key or not. */
+ iIsPrimaryKey = 0;
+ for (iPrimaryKeyIndex = 0; (*tpPKeys)[iPrimaryKeyIndex] != 0;
+ iPrimaryKeyIndex++)
+ {
+ if ((*tpPKeys)[iPrimaryKeyIndex] == iColumnCounter)
+ {
+ iIsPrimaryKey = 1;
+ break;
+ }
+ }
+ if (iIsPrimaryKey ? (eKeyUsage != PRIMARY) : (eKeyUsage != NONPRIMARY))
+ {
+ /**
+ * Don't use.
+ */
#if defined DEBUG_OUTPUT
- elog(NOTICE,cpFieldName);
+ elog(NOTICE, "Skipping column");
#endif
- while(iDataBlockSize - iUsedDataBlock < strlen(cpFieldName) +4) {
- cpDataBlock = SPI_repalloc(cpDataBlock,iDataBlockSize + BUFFER_SIZE);
- iDataBlockSize = iDataBlockSize + BUFFER_SIZE;
- }
- sprintf(cpDataBlock+iUsedDataBlock,"\"%s\"=",cpFieldName);
- iUsedDataBlock = iUsedDataBlock + strlen(cpFieldName)+3;
- cpFieldData=SPI_getvalue(tTupleData,tTupleDesc,iColumnCounter);
-
- cpUnFormatedPtr = cpFieldData;
- cpFormatedPtr = cpDataBlock + iUsedDataBlock;
- if(cpFieldData!=NULL) {
- *cpFormatedPtr='\'';
- iUsedDataBlock++;
- cpFormatedPtr++;
- }
- else {
- *cpFormatedPtr=' ';
- iUsedDataBlock++;
- cpFormatedPtr++;
- continue;
-
- }
+ continue;
+ }
+ } /* KeyUsage!=ALL */
+ cpFieldName = DatumGetPointer(NameGetDatum(&tTupleDesc->attrs
+ [iColumnCounter - 1]->attname));
#if defined DEBUG_OUTPUT
- elog(NOTICE,cpFieldData);
- elog(NOTICE,"Starting format loop");
+ elog(NOTICE, cpFieldName);
#endif
- while(*cpUnFormatedPtr!=0) {
- while(iDataBlockSize - iUsedDataBlock < 2) {
- cpDataBlock = SPI_repalloc(cpDataBlock,iDataBlockSize+BUFFER_SIZE);
- iDataBlockSize = iDataBlockSize + BUFFER_SIZE;
- cpFormatedPtr = cpDataBlock + iUsedDataBlock;
- }
- if(*cpUnFormatedPtr=='\\' || *cpUnFormatedPtr=='\'') {
- *cpFormatedPtr='\\';
- cpFormatedPtr++;
- iUsedDataBlock++;
- }
- *cpFormatedPtr=*cpUnFormatedPtr;
- cpFormatedPtr++;
- cpUnFormatedPtr++;
- iUsedDataBlock++;
- }
-
- SPI_pfree(cpFieldData);
-
- while(iDataBlockSize - iUsedDataBlock < 3) {
- cpDataBlock = SPI_repalloc(cpDataBlock,iDataBlockSize+BUFFER_SIZE);
- iDataBlockSize = iDataBlockSize + BUFFER_SIZE;
- cpFormatedPtr = cpDataBlock + iUsedDataBlock;
- }
- sprintf(cpFormatedPtr,"' ");
- iUsedDataBlock = iUsedDataBlock +2;
+ while (iDataBlockSize - iUsedDataBlock < strlen(cpFieldName) + 4)
+ {
+ cpDataBlock = SPI_repalloc(cpDataBlock, iDataBlockSize + BUFFER_SIZE);
+ iDataBlockSize = iDataBlockSize + BUFFER_SIZE;
+ }
+ sprintf(cpDataBlock + iUsedDataBlock, "\"%s\"=", cpFieldName);
+ iUsedDataBlock = iUsedDataBlock + strlen(cpFieldName) + 3;
+ cpFieldData = SPI_getvalue(tTupleData, tTupleDesc, iColumnCounter);
+
+ cpUnFormatedPtr = cpFieldData;
+ cpFormatedPtr = cpDataBlock + iUsedDataBlock;
+ if (cpFieldData != NULL)
+ {
+ *cpFormatedPtr = '\'';
+ iUsedDataBlock++;
+ cpFormatedPtr++;
+ }
+ else
+ {
+ *cpFormatedPtr = ' ';
+ iUsedDataBlock++;
+ cpFormatedPtr++;
+ continue;
+
+ }
#if defined DEBUG_OUTPUT
- elog(NOTICE,cpDataBlock);
+ elog(NOTICE, cpFieldData);
+ elog(NOTICE, "Starting format loop");
#endif
-
- } /* for iColumnCounter */
- if(tpPKeys!=NULL) {
- SPI_pfree(tpPKeys);
- }
+ while (*cpUnFormatedPtr != 0)
+ {
+ while (iDataBlockSize - iUsedDataBlock < 2)
+ {
+ cpDataBlock = SPI_repalloc(cpDataBlock, iDataBlockSize + BUFFER_SIZE);
+ iDataBlockSize = iDataBlockSize + BUFFER_SIZE;
+ cpFormatedPtr = cpDataBlock + iUsedDataBlock;
+ }
+ if (*cpUnFormatedPtr == '\\' || *cpUnFormatedPtr == '\'')
+ {
+ *cpFormatedPtr = '\\';
+ cpFormatedPtr++;
+ iUsedDataBlock++;
+ }
+ *cpFormatedPtr = *cpUnFormatedPtr;
+ cpFormatedPtr++;
+ cpUnFormatedPtr++;
+ iUsedDataBlock++;
+ }
+
+ SPI_pfree(cpFieldData);
+
+ while (iDataBlockSize - iUsedDataBlock < 3)
+ {
+ cpDataBlock = SPI_repalloc(cpDataBlock, iDataBlockSize + BUFFER_SIZE);
+ iDataBlockSize = iDataBlockSize + BUFFER_SIZE;
+ cpFormatedPtr = cpDataBlock + iUsedDataBlock;
+ }
+ sprintf(cpFormatedPtr, "' ");
+ iUsedDataBlock = iUsedDataBlock + 2;
#if defined DEBUG_OUTPUT
- elog(NOTICE,"Returning");
+ elog(NOTICE, cpDataBlock);
#endif
- memset(cpDataBlock + iUsedDataBlock,0,iDataBlockSize - iUsedDataBlock);
- return cpDataBlock;
-
+ } /* for iColumnCounter */
+ if (tpPKeys != NULL)
+ SPI_pfree(tpPKeys);
+#if defined DEBUG_OUTPUT
+ elog(NOTICE, "Returning");
+#endif
+ memset(cpDataBlock + iUsedDataBlock, 0, iDataBlockSize - iUsedDataBlock);
+
+ return cpDataBlock;
+
}
PG_FUNCTION_INFO_V1(database_size);
-Datum database_size(PG_FUNCTION_ARGS);
+Datum database_size(PG_FUNCTION_ARGS);
Datum
database_size(PG_FUNCTION_ARGS)
PG_FUNCTION_INFO_V1(relation_size);
-Datum relation_size(PG_FUNCTION_ARGS);
+Datum relation_size(PG_FUNCTION_ARGS);
Datum
relation_size(PG_FUNCTION_ARGS)
unsigned int segcount;
relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname,
- "relation_size"));
+ "relation_size"));
relation = heap_openrv(relrv, AccessShareLock);
relnode = relation->rd_rel->relfilenode;
SELECT count(*)::int4 \
FROM \"%s\" t1, \"%s\" t2 \
WHERE t1.\"%s\" = t2.oid ",
- relname, relname2, attname);
+ relname, relname2, attname);
else
sprintf(query, 4000, "\
DECLARE c_matches BINARY CURSOR FOR \
* This file is the property of the Digital Music Network (DMN).
* It is being made available to users of the PostgreSQL system
* under the BSD license.
- *
+ *
* NOTE: This module requires sizeof(void *) to be the same as sizeof(int)
*/
#include "postgres.h"
typedef struct
{
- ArrayType a;
- int items;
- int lower;
- int4 array[1];
-}PGARRAY;
+ ArrayType a;
+ int items;
+ int lower;
+ int4 array[1];
+} PGARRAY;
/* This is used to keep track of our position during enumeration */
typedef struct callContext
{
- PGARRAY *p;
- int num;
- int flags;
-}CTX;
+ PGARRAY *p;
+ int num;
+ int flags;
+} CTX;
#define TOASTED 1
-#define START_NUM 8
+#define START_NUM 8
#define PGARRAY_SIZE(n) (sizeof(PGARRAY) + ((n-1)*sizeof(int4)))
-static PGARRAY * GetPGArray(int4 state, int fAdd);
-static PGARRAY *ShrinkPGArray(PGARRAY *p);
+static PGARRAY *GetPGArray(int4 state, int fAdd);
+static PGARRAY *ShrinkPGArray(PGARRAY * p);
-Datum int_agg_state(PG_FUNCTION_ARGS);
-Datum int_agg_final_count(PG_FUNCTION_ARGS);
-Datum int_agg_final_array(PG_FUNCTION_ARGS);
-Datum int_enum(PG_FUNCTION_ARGS);
+Datum int_agg_state(PG_FUNCTION_ARGS);
+Datum int_agg_final_count(PG_FUNCTION_ARGS);
+Datum int_agg_final_array(PG_FUNCTION_ARGS);
+Datum int_enum(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(int_agg_state);
PG_FUNCTION_INFO_V1(int_agg_final_count);
* Manage the aggregation state of the array
* You need to specify the correct memory context, or it will vanish!
*/
-static PGARRAY * GetPGArray(int4 state, int fAdd)
+static PGARRAY *
+GetPGArray(int4 state, int fAdd)
{
- PGARRAY *p = (PGARRAY *) state;
+ PGARRAY *p = (PGARRAY *) state;
- if(!state)
+ if (!state)
{
/* New array */
- int cb = PGARRAY_SIZE(START_NUM);
+ int cb = PGARRAY_SIZE(START_NUM);
p = (PGARRAY *) MemoryContextAlloc(TopTransactionContext, cb);
- if(!p)
+ if (!p)
{
- elog(ERROR,"Integer aggregator, cant allocate TopTransactionContext memory");
+ elog(ERROR, "Integer aggregator, cant allocate TopTransactionContext memory");
return 0;
}
p->a.elemtype = INT4OID;
#endif
p->items = 0;
- p->lower= START_NUM;
+ p->lower = START_NUM;
}
- else if(fAdd)
- { /* Ensure array has space */
- if(p->items >= p->lower)
+ else if (fAdd)
+ { /* Ensure array has space */
+ if (p->items >= p->lower)
{
- PGARRAY *pn;
- int n = p->lower + p->lower;
- int cbNew = PGARRAY_SIZE(n);
+ PGARRAY *pn;
+ int n = p->lower + p->lower;
+ int cbNew = PGARRAY_SIZE(n);
pn = (PGARRAY *) repalloc(p, cbNew);
- if(!pn)
- { /* Realloc failed! Reallocate new block. */
+ if (!pn)
+ { /* Realloc failed! Reallocate new block. */
pn = (PGARRAY *) MemoryContextAlloc(TopTransactionContext, cbNew);
- if(!pn)
+ if (!pn)
{
elog(ERROR, "Integer aggregator, REALLY REALLY can't alloc memory");
return (PGARRAY *) NULL;
}
/* Shrinks the array to its actual size and moves it into the standard
- * memory allocation context, frees working memory */
-static PGARRAY *ShrinkPGArray(PGARRAY *p)
+ * memory allocation context, frees working memory */
+static PGARRAY *
+ShrinkPGArray(PGARRAY * p)
{
- PGARRAY *pnew=NULL;
- if(p)
+ PGARRAY *pnew = NULL;
+
+ if (p)
{
/* get target size */
- int cb = PGARRAY_SIZE(p->items);
+ int cb = PGARRAY_SIZE(p->items);
/* use current transaction context */
pnew = palloc(cb);
- if(pnew)
+ if (pnew)
{
- /* Fix up the fields in the new structure, so Postgres understands */
+ /*
+ * Fix up the fields in the new structure, so Postgres
+ * understands
+ */
memcpy(pnew, p, cb);
pnew->a.size = cb;
- pnew->a.ndim=1;
+ pnew->a.ndim = 1;
pnew->a.flags = 0;
#ifndef PG_7_2
pnew->a.elemtype = INT4OID;
pnew->lower = 0;
}
else
- {
elog(ERROR, "Integer aggregator, can't allocate memory");
- }
pfree(p);
}
return pnew;
}
/* Called for each iteration during an aggregate function */
-Datum int_agg_state(PG_FUNCTION_ARGS)
+Datum
+int_agg_state(PG_FUNCTION_ARGS)
{
- int4 state = PG_GETARG_INT32(0);
- int4 value = PG_GETARG_INT32(1);
+ int4 state = PG_GETARG_INT32(0);
+ int4 value = PG_GETARG_INT32(1);
- PGARRAY *p = GetPGArray(state, 1);
- if(!p)
- {
- elog(ERROR,"No aggregate storage");
- }
- else if(p->items >= p->lower)
- {
- elog(ERROR,"aggregate storage too small");
- }
+ PGARRAY *p = GetPGArray(state, 1);
+
+ if (!p)
+ elog(ERROR, "No aggregate storage");
+ else if (p->items >= p->lower)
+ elog(ERROR, "aggregate storage too small");
else
- {
- p->array[p->items++]= value;
- }
+ p->array[p->items++] = value;
PG_RETURN_INT32(p);
}
/* This is the final function used for the integer aggregator. It returns all the integers
* collected as a one dimentional integer array */
-Datum int_agg_final_array(PG_FUNCTION_ARGS)
+Datum
+int_agg_final_array(PG_FUNCTION_ARGS)
{
- PGARRAY *pnew = ShrinkPGArray(GetPGArray(PG_GETARG_INT32(0),0));
- if(pnew)
- {
+ PGARRAY *pnew = ShrinkPGArray(GetPGArray(PG_GETARG_INT32(0), 0));
+
+ if (pnew)
PG_RETURN_POINTER(pnew);
- }
else
- {
PG_RETURN_NULL();
- }
}
/* This function accepts an array, and returns one item for each entry in the array */
-Datum int_enum(PG_FUNCTION_ARGS)
+Datum
+int_enum(PG_FUNCTION_ARGS)
{
- PGARRAY *p = (PGARRAY *) PG_GETARG_POINTER(0);
- CTX *pc;
- ReturnSetInfo *rsi = (ReturnSetInfo *)fcinfo->resultinfo;
+ PGARRAY *p = (PGARRAY *) PG_GETARG_POINTER(0);
+ CTX *pc;
+ ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
if (!rsi || !IsA(rsi, ReturnSetInfo))
elog(ERROR, "No ReturnSetInfo sent! function must be declared returning a 'setof' integer");
- if(!p)
+ if (!p)
{
elog(WARNING, "No data sent");
PG_RETURN_NULL();
}
- if(!fcinfo->context)
+ if (!fcinfo->context)
{
/* Allocate a working context */
pc = (CTX *) palloc(sizeof(CTX));
/* Don't copy atribute if you don't need too */
- if(VARATT_IS_EXTENDED(p) )
+ if (VARATT_IS_EXTENDED(p))
{
/* Toasted!!! */
pc->p = (PGARRAY *) PG_DETOAST_DATUM_COPY(p);
pc->flags = TOASTED;
- if(!pc->p)
+ if (!pc->p)
{
elog(ERROR, "Error in toaster!!! no detoasting");
PG_RETURN_NULL();
pc->flags = 0;
}
fcinfo->context = (Node *) pc;
- pc->num=0;
+ pc->num = 0;
}
- else /* use an existing one */
- {
+ else
+/* use an existing one */
pc = (CTX *) fcinfo->context;
- }
/* Are we done yet? */
- if(pc->num >= pc->p->items)
+ if (pc->num >= pc->p->items)
{
/* We are done */
- if(pc->flags & TOASTED)
+ if (pc->flags & TOASTED)
pfree(pc->p);
pfree(fcinfo->context);
fcinfo->context = NULL;
- rsi->isDone = ExprEndResult ;
+ rsi->isDone = ExprEndResult;
}
- else /* nope, return the next value */
+ else
+/* nope, return the next value */
{
- int val = pc->p->array[pc->num++];
+ int val = pc->p->array[pc->num++];
+
rsi->isDone = ExprMultipleResult;
PG_RETURN_INT32(val);
}
static void
printarr(ArrayType *a, int num)
{
- StringInfoData bbb;
+ StringInfoData bbb;
char *cur;
int l;
int *d;
d = ARRPTR(a);
initStringInfo(&bbb);
for (l = 0; l < min(num, ARRNELEMS(a)); l++)
- {
appendStringInfo(&bbb, "%d ", d[l]);
- }
elog(DEBUG3, "\t\t%s", bbb.data);
pfree(bbb.data);
}
elog(DEBUG3, "BV: %s", str);
}
-
#endif
/*
/*
** GiST support methods
*/
-PG_FUNCTION_INFO_V1( g_int_consistent );
-PG_FUNCTION_INFO_V1( g_int_compress );
-PG_FUNCTION_INFO_V1( g_int_decompress );
-PG_FUNCTION_INFO_V1( g_int_penalty );
-PG_FUNCTION_INFO_V1( g_int_picksplit );
-PG_FUNCTION_INFO_V1( g_int_union );
-PG_FUNCTION_INFO_V1( g_int_same );
-
-Datum g_int_consistent(PG_FUNCTION_ARGS);
-Datum g_int_compress(PG_FUNCTION_ARGS);
-Datum g_int_decompress(PG_FUNCTION_ARGS);
-Datum g_int_penalty(PG_FUNCTION_ARGS);
-Datum g_int_picksplit(PG_FUNCTION_ARGS);
-Datum g_int_union(PG_FUNCTION_ARGS);
-Datum g_int_same(PG_FUNCTION_ARGS);
+PG_FUNCTION_INFO_V1(g_int_consistent);
+PG_FUNCTION_INFO_V1(g_int_compress);
+PG_FUNCTION_INFO_V1(g_int_decompress);
+PG_FUNCTION_INFO_V1(g_int_penalty);
+PG_FUNCTION_INFO_V1(g_int_picksplit);
+PG_FUNCTION_INFO_V1(g_int_union);
+PG_FUNCTION_INFO_V1(g_int_same);
+
+Datum g_int_consistent(PG_FUNCTION_ARGS);
+Datum g_int_compress(PG_FUNCTION_ARGS);
+Datum g_int_decompress(PG_FUNCTION_ARGS);
+Datum g_int_penalty(PG_FUNCTION_ARGS);
+Datum g_int_picksplit(PG_FUNCTION_ARGS);
+Datum g_int_union(PG_FUNCTION_ARGS);
+Datum g_int_same(PG_FUNCTION_ARGS);
/*
** R-tree support functions
*/
-static bool inner_int_contains(ArrayType *a, ArrayType *b);
-static bool inner_int_overlap(ArrayType *a, ArrayType *b);
-static ArrayType *inner_int_union(ArrayType *a, ArrayType *b);
-static ArrayType *inner_int_inter(ArrayType *a, ArrayType *b);
-static void rt__int_size(ArrayType *a, float *sz);
-
-PG_FUNCTION_INFO_V1( _int_different );
-PG_FUNCTION_INFO_V1( _int_same );
-PG_FUNCTION_INFO_V1( _int_contains );
-PG_FUNCTION_INFO_V1( _int_contained );
-PG_FUNCTION_INFO_V1( _int_overlap );
-PG_FUNCTION_INFO_V1( _int_union );
-PG_FUNCTION_INFO_V1( _int_inter );
-
-Datum _int_different(PG_FUNCTION_ARGS);
-Datum _int_same(PG_FUNCTION_ARGS);
-Datum _int_contains(PG_FUNCTION_ARGS);
-Datum _int_contained(PG_FUNCTION_ARGS);
-Datum _int_overlap(PG_FUNCTION_ARGS);
-Datum _int_union(PG_FUNCTION_ARGS);
-Datum _int_inter(PG_FUNCTION_ARGS);
+static bool inner_int_contains(ArrayType *a, ArrayType *b);
+static bool inner_int_overlap(ArrayType *a, ArrayType *b);
+static ArrayType *inner_int_union(ArrayType *a, ArrayType *b);
+static ArrayType *inner_int_inter(ArrayType *a, ArrayType *b);
+static void rt__int_size(ArrayType *a, float *sz);
+
+PG_FUNCTION_INFO_V1(_int_different);
+PG_FUNCTION_INFO_V1(_int_same);
+PG_FUNCTION_INFO_V1(_int_contains);
+PG_FUNCTION_INFO_V1(_int_contained);
+PG_FUNCTION_INFO_V1(_int_overlap);
+PG_FUNCTION_INFO_V1(_int_union);
+PG_FUNCTION_INFO_V1(_int_inter);
+
+Datum _int_different(PG_FUNCTION_ARGS);
+Datum _int_same(PG_FUNCTION_ARGS);
+Datum _int_contains(PG_FUNCTION_ARGS);
+Datum _int_contained(PG_FUNCTION_ARGS);
+Datum _int_overlap(PG_FUNCTION_ARGS);
+Datum _int_union(PG_FUNCTION_ARGS);
+Datum _int_inter(PG_FUNCTION_ARGS);
/*
** _intbig methods
*/
-PG_FUNCTION_INFO_V1( g_intbig_consistent );
-PG_FUNCTION_INFO_V1( g_intbig_compress );
-PG_FUNCTION_INFO_V1( g_intbig_decompress );
-PG_FUNCTION_INFO_V1( g_intbig_penalty );
-PG_FUNCTION_INFO_V1( g_intbig_picksplit );
-PG_FUNCTION_INFO_V1( g_intbig_union );
-PG_FUNCTION_INFO_V1( g_intbig_same );
-
-Datum g_intbig_consistent(PG_FUNCTION_ARGS);
-Datum g_intbig_compress(PG_FUNCTION_ARGS);
-Datum g_intbig_decompress(PG_FUNCTION_ARGS);
-Datum g_intbig_penalty(PG_FUNCTION_ARGS);
-Datum g_intbig_picksplit(PG_FUNCTION_ARGS);
-Datum g_intbig_union(PG_FUNCTION_ARGS);
-Datum g_intbig_same(PG_FUNCTION_ARGS);
+PG_FUNCTION_INFO_V1(g_intbig_consistent);
+PG_FUNCTION_INFO_V1(g_intbig_compress);
+PG_FUNCTION_INFO_V1(g_intbig_decompress);
+PG_FUNCTION_INFO_V1(g_intbig_penalty);
+PG_FUNCTION_INFO_V1(g_intbig_picksplit);
+PG_FUNCTION_INFO_V1(g_intbig_union);
+PG_FUNCTION_INFO_V1(g_intbig_same);
+
+Datum g_intbig_consistent(PG_FUNCTION_ARGS);
+Datum g_intbig_compress(PG_FUNCTION_ARGS);
+Datum g_intbig_decompress(PG_FUNCTION_ARGS);
+Datum g_intbig_penalty(PG_FUNCTION_ARGS);
+Datum g_intbig_picksplit(PG_FUNCTION_ARGS);
+Datum g_intbig_union(PG_FUNCTION_ARGS);
+Datum g_intbig_same(PG_FUNCTION_ARGS);
static bool _intbig_contains(ArrayType *a, ArrayType *b);
static bool _intbig_overlap(ArrayType *a, ArrayType *b);
static ArrayType *_intbig_union(ArrayType *a, ArrayType *b);
-static ArrayType * _intbig_inter(ArrayType *a, ArrayType *b);
+static ArrayType *_intbig_inter(ArrayType *a, ArrayType *b);
static void rt__intbig_size(ArrayType *a, float *sz);
/*****************************************************************************
- * Boolean Search
+ * Boolean Search
*****************************************************************************/
#define BooleanSearchStrategy 20
* item in polish notation with back link
* to left operand
*/
-typedef struct ITEM {
- int2 type;
- int2 left;
- int4 val;
-} ITEM;
-
-typedef struct {
- int4 len;
- int4 size;
- char data[1];
-} QUERYTYPE;
+typedef struct ITEM
+{
+ int2 type;
+ int2 left;
+ int4 val;
+} ITEM;
+
+typedef struct
+{
+ int4 len;
+ int4 size;
+ char data[1];
+} QUERYTYPE;
#define HDRSIZEQT ( 2*sizeof(int4) )
#define COMPUTESIZE(size) ( HDRSIZEQT + size * sizeof(ITEM) )
PG_FUNCTION_INFO_V1(bqarr_in);
PG_FUNCTION_INFO_V1(bqarr_out);
-Datum bqarr_in(PG_FUNCTION_ARGS);
-Datum bqarr_out(PG_FUNCTION_ARGS);
+Datum bqarr_in(PG_FUNCTION_ARGS);
+Datum bqarr_out(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(boolop);
-Datum boolop(PG_FUNCTION_ARGS);
+Datum boolop(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(rboolop);
-Datum rboolop(PG_FUNCTION_ARGS);
+Datum rboolop(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(querytree);
-Datum querytree(PG_FUNCTION_ARGS);
+Datum querytree(PG_FUNCTION_ARGS);
-static bool signconsistent( QUERYTYPE *query, BITVEC sign, bool leaf );
-static bool execconsistent( QUERYTYPE *query, ArrayType *array, bool leaf );
+static bool signconsistent(QUERYTYPE * query, BITVEC sign, bool leaf);
+static bool execconsistent(QUERYTYPE * query, ArrayType *array, bool leaf);
/*****************************************************************************
* GiST functions
** corresponding to strategy in the pg_amop table.
*/
Datum
-g_int_consistent(PG_FUNCTION_ARGS) {
- GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
- ArrayType *query = ( ArrayType * )PG_GETARG_POINTER(1);
+g_int_consistent(PG_FUNCTION_ARGS)
+{
+ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
+ ArrayType *query = (ArrayType *) PG_GETARG_POINTER(1);
StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
bool retval;
- if ( strategy == BooleanSearchStrategy )
- PG_RETURN_BOOL(execconsistent( (QUERYTYPE*)query,
- (ArrayType *) DatumGetPointer(entry->key),
- ISLEAFKEY( (ArrayType *) DatumGetPointer(entry->key) ) ) );
+ if (strategy == BooleanSearchStrategy)
+ PG_RETURN_BOOL(execconsistent((QUERYTYPE *) query,
+ (ArrayType *) DatumGetPointer(entry->key),
+ ISLEAFKEY((ArrayType *) DatumGetPointer(entry->key))));
/* XXX are we sure it's safe to scribble on the query object here? */
/* XXX what about toasted input? */
/* sort query for fast search, key is already sorted */
- if ( ARRISVOID( query ) )
+ if (ARRISVOID(query))
PG_RETURN_BOOL(false);
PREPAREARR(query);
query);
break;
case RTSameStrategyNumber:
- if ( GIST_LEAF(entry) )
+ if (GIST_LEAF(entry))
DirectFunctionCall3(
- g_int_same,
- entry->key,
- PointerGetDatum(query),
- PointerGetDatum(&retval)
- );
+ g_int_same,
+ entry->key,
+ PointerGetDatum(query),
+ PointerGetDatum(&retval)
+ );
else
retval = inner_int_contains((ArrayType *) DatumGetPointer(entry->key),
- query);
+ query);
break;
case RTContainsStrategyNumber:
retval = inner_int_contains((ArrayType *) DatumGetPointer(entry->key),
query);
break;
case RTContainedByStrategyNumber:
- if ( GIST_LEAF(entry) )
+ if (GIST_LEAF(entry))
retval = inner_int_contains(query,
- (ArrayType *) DatumGetPointer(entry->key) );
+ (ArrayType *) DatumGetPointer(entry->key));
else
retval = inner_int_overlap((ArrayType *) DatumGetPointer(entry->key),
- query);
+ query);
break;
default:
retval = FALSE;
Datum
g_int_union(PG_FUNCTION_ARGS)
{
- PG_RETURN_POINTER( _int_common_union(
- (bytea *) PG_GETARG_POINTER(0),
- (int *) PG_GETARG_POINTER(1),
- inner_int_union
- ) );
+ PG_RETURN_POINTER(_int_common_union(
+ (bytea *) PG_GETARG_POINTER(0),
+ (int *) PG_GETARG_POINTER(1),
+ inner_int_union
+ ));
}
/*
Datum
g_int_compress(PG_FUNCTION_ARGS)
{
- GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
+ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
GISTENTRY *retval;
ArrayType *r;
int len;
min,
cand;
- if (entry->leafkey) {
+ if (entry->leafkey)
+ {
r = (ArrayType *) PG_DETOAST_DATUM_COPY(entry->key);
PREPAREARR(r);
r->flags |= LEAFKEY;
retval = palloc(sizeof(GISTENTRY));
gistentryinit(*retval, PointerGetDatum(r),
- entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
+ entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
PG_RETURN_POINTER(retval);
}
r = (ArrayType *) PG_DETOAST_DATUM(entry->key);
- if ( ISLEAFKEY( r ) || ARRISVOID(r) ) {
- if ( r != (ArrayType*)DatumGetPointer(entry->key) )
+ if (ISLEAFKEY(r) || ARRISVOID(r))
+ {
+ if (r != (ArrayType *) DatumGetPointer(entry->key))
pfree(r);
PG_RETURN_POINTER(entry);
}
- if ( (len=ARRNELEMS(r)) >= 2 * MAXNUMRANGE) { /* compress */
- if ( r == (ArrayType*)DatumGetPointer( entry->key) )
+ if ((len = ARRNELEMS(r)) >= 2 * MAXNUMRANGE)
+ { /* compress */
+ if (r == (ArrayType *) DatumGetPointer(entry->key))
r = (ArrayType *) PG_DETOAST_DATUM_COPY(entry->key);
r = resize_intArrayType(r, 2 * (len));
r = resize_intArrayType(r, len);
retval = palloc(sizeof(GISTENTRY));
gistentryinit(*retval, PointerGetDatum(r),
- entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
+ entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
PG_RETURN_POINTER(retval);
- } else {
- PG_RETURN_POINTER(entry);
}
+ else
+ PG_RETURN_POINTER(entry);
PG_RETURN_POINTER(entry);
}
Datum
g_int_decompress(PG_FUNCTION_ARGS)
{
- GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
+ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
GISTENTRY *retval;
ArrayType *r;
int *dr,
in = (ArrayType *) PG_DETOAST_DATUM(entry->key);
- if ( ARRISVOID(in) ) {
+ if (ARRISVOID(in))
PG_RETURN_POINTER(entry);
- }
lenin = ARRNELEMS(in);
- if (lenin < 2 * MAXNUMRANGE || ISLEAFKEY( in ) ) { /* not comressed value */
- if ( in != (ArrayType *) DatumGetPointer(entry->key)) {
+ if (lenin < 2 * MAXNUMRANGE || ISLEAFKEY(in))
+ { /* not comressed value */
+ if (in != (ArrayType *) DatumGetPointer(entry->key))
+ {
retval = palloc(sizeof(GISTENTRY));
gistentryinit(*retval, PointerGetDatum(in),
- entry->rel, entry->page, entry->offset, VARSIZE(in), FALSE);
+ entry->rel, entry->page, entry->offset, VARSIZE(in), FALSE);
PG_RETURN_POINTER(retval);
}
pfree(in);
retval = palloc(sizeof(GISTENTRY));
gistentryinit(*retval, PointerGetDatum(r),
- entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
+ entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
PG_RETURN_POINTER(retval);
}
Datum
g_int_penalty(PG_FUNCTION_ARGS)
{
- PG_RETURN_POINTER( _int_common_penalty(
- (GISTENTRY *)PG_GETARG_POINTER(0),
- (GISTENTRY *)PG_GETARG_POINTER(1),
- (float *) PG_GETARG_POINTER(2),
- inner_int_union, rt__int_size
- ) );
+ PG_RETURN_POINTER(_int_common_penalty(
+ (GISTENTRY *) PG_GETARG_POINTER(0),
+ (GISTENTRY *) PG_GETARG_POINTER(1),
+ (float *) PG_GETARG_POINTER(2),
+ inner_int_union, rt__int_size
+ ));
}
Datum
g_int_picksplit(PG_FUNCTION_ARGS)
{
- PG_RETURN_POINTER( _int_common_picksplit(
- (bytea *)PG_GETARG_POINTER(0),
- (GIST_SPLITVEC *)PG_GETARG_POINTER(1),
- inner_int_union,
- inner_int_inter,
- rt__int_size,
- 0.01
- ) );
+ PG_RETURN_POINTER(_int_common_picksplit(
+ (bytea *) PG_GETARG_POINTER(0),
+ (GIST_SPLITVEC *) PG_GETARG_POINTER(1),
+ inner_int_union,
+ inner_int_inter,
+ rt__int_size,
+ 0.01
+ ));
}
/*
Datum
g_int_same(PG_FUNCTION_ARGS)
{
- ArrayType *a = (ArrayType*)PointerGetDatum(PG_GETARG_POINTER(0));
- ArrayType *b = (ArrayType*)PointerGetDatum(PG_GETARG_POINTER(1));
- bool *result = (bool *)PG_GETARG_POINTER(2);
- int4 n = ARRNELEMS(a);
- int4 *da, *db;
+ ArrayType *a = (ArrayType *) PointerGetDatum(PG_GETARG_POINTER(0));
+ ArrayType *b = (ArrayType *) PointerGetDatum(PG_GETARG_POINTER(1));
+ bool *result = (bool *) PG_GETARG_POINTER(2);
+ int4 n = ARRNELEMS(a);
+ int4 *da,
+ *db;
- if ( n != ARRNELEMS(b) ) {
+ if (n != ARRNELEMS(b))
+ {
*result = false;
PG_RETURN_POINTER(result);
}
*result = TRUE;
da = ARRPTR(a);
db = ARRPTR(b);
- while(n--)
- if (*da++ != *db++) {
+ while (n--)
+ if (*da++ != *db++)
+ {
*result = FALSE;
break;
}
Datum
_int_contained(PG_FUNCTION_ARGS)
{
- PG_RETURN_BOOL( DatumGetBool(
- DirectFunctionCall2(
- _int_contains,
- PointerGetDatum(PG_GETARG_POINTER(1)),
- PointerGetDatum(PG_GETARG_POINTER(0))
- )
- ));
+ PG_RETURN_BOOL(DatumGetBool(
+ DirectFunctionCall2(
+ _int_contains,
+ PointerGetDatum(PG_GETARG_POINTER(1)),
+ PointerGetDatum(PG_GETARG_POINTER(0))
+ )
+ ));
}
Datum
_int_contains(PG_FUNCTION_ARGS)
{
- ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
- ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+ ArrayType *b = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
bool res;
if (ARRISVOID(a) || ARRISVOID(b))
res = inner_int_contains(a, b);
pfree(a);
pfree(b);
- PG_RETURN_BOOL( res );
+ PG_RETURN_BOOL(res);
}
static bool
Datum
_int_different(PG_FUNCTION_ARGS)
{
- PG_RETURN_BOOL( ! DatumGetBool(
- DirectFunctionCall2(
- _int_same,
- PointerGetDatum(PG_GETARG_POINTER(0)),
- PointerGetDatum(PG_GETARG_POINTER(1))
- )
- ));
+ PG_RETURN_BOOL(!DatumGetBool(
+ DirectFunctionCall2(
+ _int_same,
+ PointerGetDatum(PG_GETARG_POINTER(0)),
+ PointerGetDatum(PG_GETARG_POINTER(1))
+ )
+ ));
}
Datum
_int_same(PG_FUNCTION_ARGS)
{
- ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
- ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+ ArrayType *b = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
int na,
nb;
int n;
Datum
_int_overlap(PG_FUNCTION_ARGS)
{
- ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
- ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+ ArrayType *b = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
bool result;
if (ARRISVOID(a) || ARRISVOID(b))
pfree(a);
pfree(b);
- PG_RETURN_BOOL( result );
+ PG_RETURN_BOOL(result);
}
static bool
Datum
_int_union(PG_FUNCTION_ARGS)
{
- ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
- ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+ ArrayType *b = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
ArrayType *result;
if (!ARRISVOID(a))
if (b)
pfree(b);
- PG_RETURN_POINTER( result );
+ PG_RETURN_POINTER(result);
}
-static ArrayType *
+static ArrayType *
inner_int_union(ArrayType *a, ArrayType *b)
{
ArrayType *r = NULL;
Datum
_int_inter(PG_FUNCTION_ARGS)
{
- ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
- ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+ ArrayType *b = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
ArrayType *result;
if (ARRISVOID(a) || ARRISVOID(b))
pfree(a);
pfree(b);
- PG_RETURN_POINTER( result );
+ PG_RETURN_POINTER(result);
}
-static ArrayType *
+static ArrayType *
inner_int_inter(ArrayType *a, ArrayType *b)
{
ArrayType *r;
static bool
isort(int4 *a, int len)
{
- int4 tmp,
+ int4 tmp,
index;
- int4 *cur,
+ int4 *cur,
*end;
bool r = FALSE;
BITVECP bv = SIGPTR(a);
LOOPBYTE(
- len +=
- GETBITBYTE(bv,0) +
- GETBITBYTE(bv,1) +
- GETBITBYTE(bv,2) +
- GETBITBYTE(bv,3) +
- GETBITBYTE(bv,4) +
- GETBITBYTE(bv,5) +
- GETBITBYTE(bv,6) +
- GETBITBYTE(bv,7) ;
- bv = (BITVECP) ( ((char*)bv) + 1 );
+ len +=
+ GETBITBYTE(bv, 0) +
+ GETBITBYTE(bv, 1) +
+ GETBITBYTE(bv, 2) +
+ GETBITBYTE(bv, 3) +
+ GETBITBYTE(bv, 4) +
+ GETBITBYTE(bv, 5) +
+ GETBITBYTE(bv, 6) +
+ GETBITBYTE(bv, 7);
+ bv = (BITVECP) (((char *) bv) + 1);
);
*sz = (float) len;
Datum
g_intbig_same(PG_FUNCTION_ARGS)
{
- ArrayType *a = (ArrayType *)PG_GETARG_POINTER(0);
- ArrayType *b = (ArrayType *)PG_GETARG_POINTER(1);
- bool *result = (bool *)PG_GETARG_POINTER(2);
+ ArrayType *a = (ArrayType *) PG_GETARG_POINTER(0);
+ ArrayType *b = (ArrayType *) PG_GETARG_POINTER(1);
+ bool *result = (bool *) PG_GETARG_POINTER(2);
BITVECP da,
db;
int i;
db = SIGPTR(b);
LOOPBYTE(
- if (da[i] != db[i])
- {
+ if (da[i] != db[i])
+ {
*result = FALSE;
- PG_RETURN_POINTER( result );
+ PG_RETURN_POINTER(result);
}
);
*result = TRUE;
- PG_RETURN_POINTER( result );
+ PG_RETURN_POINTER(result);
}
Datum
g_intbig_compress(PG_FUNCTION_ARGS)
{
- GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
+ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
GISTENTRY *retval;
ArrayType *r,
*in;
- bool maycompress = true;
- int i;
+ bool maycompress = true;
+ int i;
if (DatumGetPointer(entry->key) != NULL)
in = (ArrayType *) PG_DETOAST_DATUM(entry->key);
else
in = NULL;
- if (!entry->leafkey) {
+ if (!entry->leafkey)
+ {
LOOPBYTE(
- if ( ( ((char*)ARRPTR(in))[i] & 0xff ) != 0xff ) {
- maycompress = false;
- break;
- }
+ if ((((char *) ARRPTR(in))[i] & 0xff) != 0xff)
+ {
+ maycompress = false;
+ break;
+ }
);
- if ( maycompress ) {
+ if (maycompress)
+ {
retval = palloc(sizeof(GISTENTRY));
r = new_intArrayType(1);
gistentryinit(*retval, PointerGetDatum(r),
- entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
- PG_RETURN_POINTER( retval );
+ entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
+ PG_RETURN_POINTER(retval);
}
- PG_RETURN_POINTER( entry );
+ PG_RETURN_POINTER(entry);
}
retval = palloc(sizeof(GISTENTRY));
- r = new_intArrayType( SIGLENINT );
+ r = new_intArrayType(SIGLENINT);
if (ARRISVOID(in))
{
gistentryinit(*retval, PointerGetDatum(r),
entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
if (in != (ArrayType *) DatumGetPointer(entry->key))
- pfree(in);
- PG_RETURN_POINTER (retval);
+ pfree(in);
+ PG_RETURN_POINTER(retval);
}
gensign(SIGPTR(r),
ARRNELEMS(in));
LOOPBYTE(
- if( ( ((char*)ARRPTR(in))[i] & 0xff ) != 0xff ) {
- maycompress = false;
- break;
- }
+ if ((((char *) ARRPTR(in))[i] & 0xff) != 0xff)
+ {
+ maycompress = false;
+ break;
+ }
);
- if ( maycompress ) {
+ if (maycompress)
+ {
pfree(r);
r = new_intArrayType(1);
}
gistentryinit(*retval, PointerGetDatum(r), entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
- if ( in != (ArrayType *) DatumGetPointer(entry->key))
- pfree(in);
+ if (in != (ArrayType *) DatumGetPointer(entry->key))
+ pfree(in);
- PG_RETURN_POINTER (retval);
+ PG_RETURN_POINTER(retval);
}
Datum
g_intbig_decompress(PG_FUNCTION_ARGS)
{
- GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
+ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
ArrayType *key;
key = (ArrayType *) PG_DETOAST_DATUM(entry->key);
- if ( key != (ArrayType *) DatumGetPointer(entry->key))
+ if (key != (ArrayType *) DatumGetPointer(entry->key))
{
GISTENTRY *retval;
retval = palloc(sizeof(GISTENTRY));
gistentryinit(*retval, PointerGetDatum(key),
- entry->rel, entry->page, entry->offset, (key) ? VARSIZE(key) : 0, FALSE);
- PG_RETURN_POINTER( retval );
+ entry->rel, entry->page, entry->offset, (key) ? VARSIZE(key) : 0, FALSE);
+ PG_RETURN_POINTER(retval);
}
- if ( ARRNELEMS(key) == 1 ) {
+ if (ARRNELEMS(key) == 1)
+ {
GISTENTRY *retval;
ArrayType *newkey;
retval = palloc(sizeof(GISTENTRY));
newkey = new_intArrayType(SIGLENINT);
- MemSet( (void*)ARRPTR(newkey), 0xff, SIGLEN );
+ MemSet((void *) ARRPTR(newkey), 0xff, SIGLEN);
gistentryinit(*retval, PointerGetDatum(newkey),
- entry->rel, entry->page, entry->offset, VARSIZE(newkey), FALSE);
- PG_RETURN_POINTER( retval );
+ entry->rel, entry->page, entry->offset, VARSIZE(newkey), FALSE);
+ PG_RETURN_POINTER(retval);
}
- PG_RETURN_POINTER( entry );
+ PG_RETURN_POINTER(entry);
}
Datum
g_intbig_picksplit(PG_FUNCTION_ARGS)
{
- PG_RETURN_POINTER( _int_common_picksplit(
- (bytea *)PG_GETARG_POINTER(0),
- (GIST_SPLITVEC *)PG_GETARG_POINTER(1),
- _intbig_union,
- _intbig_inter,
- rt__intbig_size,
- 0.1
- ) );
+ PG_RETURN_POINTER(_int_common_picksplit(
+ (bytea *) PG_GETARG_POINTER(0),
+ (GIST_SPLITVEC *) PG_GETARG_POINTER(1),
+ _intbig_union,
+ _intbig_inter,
+ rt__intbig_size,
+ 0.1
+ ));
}
Datum
g_intbig_union(PG_FUNCTION_ARGS)
{
- PG_RETURN_POINTER( _int_common_union(
- (bytea *) PG_GETARG_POINTER(0),
- (int *) PG_GETARG_POINTER(1),
- _intbig_union
- ) );
+ PG_RETURN_POINTER(_int_common_union(
+ (bytea *) PG_GETARG_POINTER(0),
+ (int *) PG_GETARG_POINTER(1),
+ _intbig_union
+ ));
}
Datum
g_intbig_penalty(PG_FUNCTION_ARGS)
{
- PG_RETURN_POINTER( _int_common_penalty(
- (GISTENTRY *)PG_GETARG_POINTER(0),
- (GISTENTRY *)PG_GETARG_POINTER(1),
- (float *) PG_GETARG_POINTER(2),
- _intbig_union, rt__intbig_size
- ) );
+ PG_RETURN_POINTER(_int_common_penalty(
+ (GISTENTRY *) PG_GETARG_POINTER(0),
+ (GISTENTRY *) PG_GETARG_POINTER(1),
+ (float *) PG_GETARG_POINTER(2),
+ _intbig_union, rt__intbig_size
+ ));
}
Datum
-g_intbig_consistent(PG_FUNCTION_ARGS) {
- GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
- ArrayType *query = ( ArrayType * )PG_GETARG_POINTER(1);
- StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
+g_intbig_consistent(PG_FUNCTION_ARGS)
+{
+ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
+ ArrayType *query = (ArrayType *) PG_GETARG_POINTER(1);
+ StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
bool retval;
ArrayType *q;
- if ( strategy == BooleanSearchStrategy )
- PG_RETURN_BOOL(signconsistent( (QUERYTYPE*)query,
- SIGPTR((ArrayType *) DatumGetPointer(entry->key)),
- false ) );
+ if (strategy == BooleanSearchStrategy)
+ PG_RETURN_BOOL(signconsistent((QUERYTYPE *) query,
+ SIGPTR((ArrayType *) DatumGetPointer(entry->key)),
+ false));
/* XXX what about toasted input? */
if (ARRISVOID(query))
retval = _intbig_overlap((ArrayType *) DatumGetPointer(entry->key), q);
break;
case RTSameStrategyNumber:
- if ( GIST_LEAF(entry) )
+ if (GIST_LEAF(entry))
DirectFunctionCall3(
- g_intbig_same,
- entry->key,
- PointerGetDatum(q),
- PointerGetDatum(&retval)
- );
+ g_intbig_same,
+ entry->key,
+ PointerGetDatum(q),
+ PointerGetDatum(&retval)
+ );
else
retval = _intbig_contains((ArrayType *) DatumGetPointer(entry->key), q);
break;
** The GiST Union method for _intments
** returns the minimal set that encloses all the entries in entryvec
*/
-static ArrayType *
+static ArrayType *
_int_common_union(bytea *entryvec, int *sizep, formarray unionf)
{
int numranges,
for (i = 1; i < numranges; i++)
{
out = (*unionf) (tmp, (ArrayType *)
- DatumGetPointer(((GISTENTRY *) VARDATA(entryvec))[i].key));
+ DatumGetPointer(((GISTENTRY *) VARDATA(entryvec))[i].key));
if (i > 1 && tmp)
pfree(tmp);
tmp = out;
return (result);
}
-typedef struct {
- OffsetNumber pos;
+typedef struct
+{
+ OffsetNumber pos;
float cost;
} SPLITCOST;
static int
-comparecost( const void *a, const void *b ) {
- if ( ((SPLITCOST*)a)->cost == ((SPLITCOST*)b)->cost )
+comparecost(const void *a, const void *b)
+{
+ if (((SPLITCOST *) a)->cost == ((SPLITCOST *) b)->cost)
return 0;
else
- return ( ((SPLITCOST*)a)->cost > ((SPLITCOST*)b)->cost ) ? 1 : -1;
+ return (((SPLITCOST *) a)->cost > ((SPLITCOST *) b)->cost) ? 1 : -1;
}
/*
OffsetNumber *left,
*right;
OffsetNumber maxoff;
- SPLITCOST *costvector;
+ SPLITCOST *costvector;
#ifdef GIST_DEBUG
elog(DEBUG3, "--------picksplit %d", (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY));
v->spl_nleft = 0;
right = v->spl_right;
v->spl_nright = 0;
- if ( seed_1 == 0 || seed_2 == 0 ) {
+ if (seed_1 == 0 || seed_2 == 0)
+ {
seed_1 = 1;
seed_2 = 2;
}
(*sizef) (datum_r, &size_r);
maxoff = OffsetNumberNext(maxoff);
+
/*
- * sort entries
+ * sort entries
*/
- costvector=(SPLITCOST*)palloc( sizeof(SPLITCOST)*maxoff );
- for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i)) {
- costvector[i-1].pos = i;
+ costvector = (SPLITCOST *) palloc(sizeof(SPLITCOST) * maxoff);
+ for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
+ {
+ costvector[i - 1].pos = i;
datum_alpha = (ArrayType *) DatumGetPointer(((GISTENTRY *) VARDATA(entryvec))[i].key);
- union_d = (*unionf)(datum_l, datum_alpha);
- (*sizef)(union_d, &size_alpha);
- pfree( union_d );
- union_d = (*unionf)(datum_r, datum_alpha);
- (*sizef)(union_d, &size_beta);
- pfree( union_d );
- costvector[i-1].cost = abs( (size_alpha - size_l) - (size_beta - size_r) );
+ union_d = (*unionf) (datum_l, datum_alpha);
+ (*sizef) (union_d, &size_alpha);
+ pfree(union_d);
+ union_d = (*unionf) (datum_r, datum_alpha);
+ (*sizef) (union_d, &size_beta);
+ pfree(union_d);
+ costvector[i - 1].cost = abs((size_alpha - size_l) - (size_beta - size_r));
}
- qsort( (void*)costvector, maxoff, sizeof(SPLITCOST), comparecost );
+ qsort((void *) costvector, maxoff, sizeof(SPLITCOST), comparecost);
/*
* Now split up the regions between the two seeds. An important
*/
- for (j = 0; j < maxoff; j++) {
+ for (j = 0; j < maxoff; j++)
+ {
i = costvector[j].pos;
/*
v->spl_nright++;
}
}
- pfree( costvector );
+ pfree(costvector);
*right = *left = FirstOffsetNumber;
datum_l->flags &= ~LEAFKEY;
}
/*****************************************************************************
- * BoolSearch
+ * BoolSearch
*****************************************************************************/
-#define END 0
-#define ERR 1
-#define VAL 2
-#define OPR 3
-#define OPEN 4
-#define CLOSE 5
+#define END 0
+#define ERR 1
+#define VAL 2
+#define OPR 3
+#define OPEN 4
+#define CLOSE 5
/* parser's states */
-#define WAITOPERAND 1
+#define WAITOPERAND 1
#define WAITENDOPERAND 2
#define WAITOPERATOR 3
* node of query tree, also used
* for storing polish notation in parser
*/
-typedef struct NODE {
- int4 type;
- int4 val;
- struct NODE *next;
-} NODE;
-
-typedef struct {
- char *buf;
- int4 state;
- int4 count;
- /* reverse polish notation in list (for temprorary usage)*/
- NODE *str;
+typedef struct NODE
+{
+ int4 type;
+ int4 val;
+ struct NODE *next;
+} NODE;
+
+typedef struct
+{
+ char *buf;
+ int4 state;
+ int4 count;
+ /* reverse polish notation in list (for temprorary usage) */
+ NODE *str;
/* number in str */
- int4 num;
-} WORKSTATE;
+ int4 num;
+} WORKSTATE;
/*
* get token from query string
*/
static int4
-gettoken( WORKSTATE* state, int4* val ) {
- char nnn[16], *curnnn;
+gettoken(WORKSTATE * state, int4 *val)
+{
+ char nnn[16],
+ *curnnn;
- curnnn=nnn;
- while(1) {
- switch(state->state) {
+ curnnn = nnn;
+ while (1)
+ {
+ switch (state->state)
+ {
case WAITOPERAND:
- curnnn=nnn;
- if ( (*(state->buf)>='0' && *(state->buf)<='9') ||
- *(state->buf)=='-' ) {
+ curnnn = nnn;
+ if ((*(state->buf) >= '0' && *(state->buf) <= '9') ||
+ *(state->buf) == '-')
+ {
state->state = WAITENDOPERAND;
*curnnn = *(state->buf);
curnnn++;
- } else if ( *(state->buf) == '!' ) {
+ }
+ else if (*(state->buf) == '!')
+ {
(state->buf)++;
- *val = (int4)'!';
+ *val = (int4) '!';
return OPR;
- } else if ( *(state->buf) == '(' ) {
+ }
+ else if (*(state->buf) == '(')
+ {
state->count++;
(state->buf)++;
return OPEN;
- } else if ( *(state->buf) != ' ' )
+ }
+ else if (*(state->buf) != ' ')
return ERR;
break;
case WAITENDOPERAND:
- if ( *(state->buf)>='0' && *(state->buf)<='9' ) {
+ if (*(state->buf) >= '0' && *(state->buf) <= '9')
+ {
*curnnn = *(state->buf);
curnnn++;
- } else {
+ }
+ else
+ {
*curnnn = '\0';
- *val=(int4)atoi( nnn );
+ *val = (int4) atoi(nnn);
state->state = WAITOPERATOR;
- return ( state->count && *(state->buf) == '\0' )
+ return (state->count && *(state->buf) == '\0')
? ERR : VAL;
}
break;
case WAITOPERATOR:
- if ( *(state->buf) == '&' || *(state->buf) == '|' ) {
+ if (*(state->buf) == '&' || *(state->buf) == '|')
+ {
state->state = WAITOPERAND;
*val = (int4) *(state->buf);
(state->buf)++;
return OPR;
- } else if ( *(state->buf) == ')' ) {
+ }
+ else if (*(state->buf) == ')')
+ {
(state->buf)++;
state->count--;
- return ( state->count <0 ) ? ERR : CLOSE;
- } else if ( *(state->buf) == '\0' ) {
- return ( state->count ) ? ERR : END;
- } else if ( *(state->buf) != ' ' )
+ return (state->count < 0) ? ERR : CLOSE;
+ }
+ else if (*(state->buf) == '\0')
+ return (state->count) ? ERR : END;
+ else if (*(state->buf) != ' ')
return ERR;
break;
default:
* push new one in polish notation reverse view
*/
static void
-pushquery( WORKSTATE *state, int4 type, int4 val ) {
- NODE *tmp = (NODE*)palloc(sizeof(NODE));
- tmp->type=type;
- tmp->val =val;
+pushquery(WORKSTATE * state, int4 type, int4 val)
+{
+ NODE *tmp = (NODE *) palloc(sizeof(NODE));
+
+ tmp->type = type;
+ tmp->val = val;
tmp->next = state->str;
state->str = tmp;
state->num++;
* make polish notaion of query
*/
static int4
-makepol(WORKSTATE *state) {
- int4 val,type;
- int4 stack[STACKDEPTH];
- int4 lenstack=0;
+makepol(WORKSTATE * state)
+{
+ int4 val,
+ type;
+ int4 stack[STACKDEPTH];
+ int4 lenstack = 0;
- while( (type=gettoken(state, &val))!=END ) {
- switch(type) {
+ while ((type = gettoken(state, &val)) != END)
+ {
+ switch (type)
+ {
case VAL:
pushquery(state, type, val);
- while ( lenstack && (stack[ lenstack-1 ] == (int4)'&' ||
- stack[ lenstack-1 ] == (int4)'!') ) {
+ while (lenstack && (stack[lenstack - 1] == (int4) '&' ||
+ stack[lenstack - 1] == (int4) '!'))
+ {
lenstack--;
- pushquery(state, OPR, stack[ lenstack ]);
+ pushquery(state, OPR, stack[lenstack]);
}
break;
case OPR:
- if ( lenstack && val == (int4) '|' ) {
+ if (lenstack && val == (int4) '|')
pushquery(state, OPR, val);
- } else {
- if ( lenstack == STACKDEPTH )
- elog(ERROR,"Stack too short");
- stack[ lenstack ] = val;
+ else
+ {
+ if (lenstack == STACKDEPTH)
+ elog(ERROR, "Stack too short");
+ stack[lenstack] = val;
lenstack++;
}
break;
case OPEN:
- if ( makepol( state ) == ERR ) return ERR;
- if ( lenstack && (stack[ lenstack-1 ] == (int4)'&' ||
- stack[ lenstack-1 ] == (int4)'!') ) {
+ if (makepol(state) == ERR)
+ return ERR;
+ if (lenstack && (stack[lenstack - 1] == (int4) '&' ||
+ stack[lenstack - 1] == (int4) '!'))
+ {
lenstack--;
- pushquery(state, OPR, stack[ lenstack ]);
+ pushquery(state, OPR, stack[lenstack]);
}
break;
case CLOSE:
- while ( lenstack ) {
+ while (lenstack)
+ {
lenstack--;
- pushquery(state, OPR, stack[ lenstack ]);
+ pushquery(state, OPR, stack[lenstack]);
};
return END;
break;
case ERR:
default:
- elog(ERROR,"Syntax error");
+ elog(ERROR, "Syntax error");
return ERR;
}
}
- while (lenstack) {
+ while (lenstack)
+ {
lenstack--;
- pushquery(state, OPR, stack[ lenstack ]);
+ pushquery(state, OPR, stack[lenstack]);
};
return END;
}
-typedef struct {
- int4 *arrb;
- int4 *arre;
-} CHKVAL;
+typedef struct
+{
+ int4 *arrb;
+ int4 *arre;
+} CHKVAL;
/*
* is there value 'val' in array or not ?
*/
static bool
-checkcondition_arr( void *checkval, int4 val ) {
- int4 *StopLow = ((CHKVAL*)checkval)->arrb;
- int4 *StopHigh = ((CHKVAL*)checkval)->arre;
- int4 *StopMiddle;
+checkcondition_arr(void *checkval, int4 val)
+{
+ int4 *StopLow = ((CHKVAL *) checkval)->arrb;
+ int4 *StopHigh = ((CHKVAL *) checkval)->arre;
+ int4 *StopMiddle;
/* Loop invariant: StopLow <= val < StopHigh */
- while (StopLow < StopHigh) {
+ while (StopLow < StopHigh)
+ {
StopMiddle = StopLow + (StopHigh - StopLow) / 2;
if (*StopMiddle == val)
return (true);
- else if (*StopMiddle < val )
+ else if (*StopMiddle < val)
StopLow = StopMiddle + 1;
else
StopHigh = StopMiddle;
}
static bool
-checkcondition_bit( void *checkval, int4 val ) {
- return GETBIT( checkval, HASHVAL( val ) );
+checkcondition_bit(void *checkval, int4 val)
+{
+ return GETBIT(checkval, HASHVAL(val));
}
/*
* check for boolean condition
*/
static bool
-execute( ITEM* curitem, void *checkval, bool calcnot, bool (*chkcond)(void *checkval, int4 val )) {
+execute(ITEM * curitem, void *checkval, bool calcnot, bool (*chkcond) (void *checkval, int4 val))
+{
- if ( curitem->type == VAL ) {
- return (*chkcond)( checkval, curitem->val );
- } else if ( curitem->val == (int4)'!' ) {
- return ( calcnot ) ?
- ( ( execute(curitem - 1, checkval, calcnot, chkcond) ) ? false : true )
+ if (curitem->type == VAL)
+ return (*chkcond) (checkval, curitem->val);
+ else if (curitem->val == (int4) '!')
+ {
+ return (calcnot) ?
+ ((execute(curitem - 1, checkval, calcnot, chkcond)) ? false : true)
: true;
- } else if ( curitem->val == (int4)'&' ) {
- if ( execute(curitem + curitem->left, checkval, calcnot, chkcond) )
+ }
+ else if (curitem->val == (int4) '&')
+ {
+ if (execute(curitem + curitem->left, checkval, calcnot, chkcond))
return execute(curitem - 1, checkval, calcnot, chkcond);
else
return false;
- } else { /* |-operator */
- if ( execute(curitem + curitem->left, checkval, calcnot, chkcond) )
+ }
+ else
+ { /* |-operator */
+ if (execute(curitem + curitem->left, checkval, calcnot, chkcond))
return true;
else
return execute(curitem - 1, checkval, calcnot, chkcond);
* signconsistent & execconsistent called by *_consistent
*/
static bool
-signconsistent( QUERYTYPE *query, BITVEC sign, bool calcnot ) {
+signconsistent(QUERYTYPE * query, BITVEC sign, bool calcnot)
+{
return execute(
- GETQUERY(query) + query->size-1 ,
- (void*)sign, calcnot,
- checkcondition_bit
+ GETQUERY(query) + query->size - 1,
+ (void *) sign, calcnot,
+ checkcondition_bit
);
}
static bool
-execconsistent( QUERYTYPE *query, ArrayType *array, bool calcnot ) {
- CHKVAL chkval;
+execconsistent(QUERYTYPE * query, ArrayType *array, bool calcnot)
+{
+ CHKVAL chkval;
chkval.arrb = ARRPTR(array);
chkval.arre = chkval.arrb + ARRNELEMS(array);
return execute(
- GETQUERY(query) + query->size-1 ,
- (void*)&chkval, calcnot,
- checkcondition_arr
- );
+ GETQUERY(query) + query->size - 1,
+ (void *) &chkval, calcnot,
+ checkcondition_arr
+ );
}
/*
* boolean operations
*/
Datum
-rboolop(PG_FUNCTION_ARGS) {
+rboolop(PG_FUNCTION_ARGS)
+{
return DirectFunctionCall2(
- boolop,
- PG_GETARG_DATUM(1),
- PG_GETARG_DATUM(0)
+ boolop,
+ PG_GETARG_DATUM(1),
+ PG_GETARG_DATUM(0)
);
}
Datum
-boolop(PG_FUNCTION_ARGS) {
- ArrayType *val = ( ArrayType * )PG_DETOAST_DATUM_COPY(PG_GETARG_POINTER(0));
- QUERYTYPE *query = ( QUERYTYPE * )PG_DETOAST_DATUM(PG_GETARG_POINTER(1));
- CHKVAL chkval;
- bool result;
+boolop(PG_FUNCTION_ARGS)
+{
+ ArrayType *val = (ArrayType *) PG_DETOAST_DATUM_COPY(PG_GETARG_POINTER(0));
+ QUERYTYPE *query = (QUERYTYPE *) PG_DETOAST_DATUM(PG_GETARG_POINTER(1));
+ CHKVAL chkval;
+ bool result;
- if ( ARRISVOID( val ) ) {
+ if (ARRISVOID(val))
+ {
pfree(val);
- PG_FREE_IF_COPY(query,1);
- PG_RETURN_BOOL( false );
+ PG_FREE_IF_COPY(query, 1);
+ PG_RETURN_BOOL(false);
}
PREPAREARR(val);
chkval.arrb = ARRPTR(val);
chkval.arre = chkval.arrb + ARRNELEMS(val);
result = execute(
- GETQUERY(query) + query->size-1 ,
- &chkval, true,
- checkcondition_arr
- );
+ GETQUERY(query) + query->size - 1,
+ &chkval, true,
+ checkcondition_arr
+ );
pfree(val);
- PG_FREE_IF_COPY(query,1);
- PG_RETURN_BOOL( result );
+ PG_FREE_IF_COPY(query, 1);
+ PG_RETURN_BOOL(result);
}
static void
-findoprnd( ITEM *ptr, int4 *pos ) {
+findoprnd(ITEM * ptr, int4 *pos)
+{
#ifdef BS_DEBUG
- elog(DEBUG3, ( ptr[*pos].type == OPR ) ?
- "%d %c" : "%d %d ", *pos, ptr[*pos].val );
+ elog(DEBUG3, (ptr[*pos].type == OPR) ?
+ "%d %c" : "%d %d ", *pos, ptr[*pos].val);
#endif
- if ( ptr[*pos].type == VAL ) {
+ if (ptr[*pos].type == VAL)
+ {
ptr[*pos].left = 0;
(*pos)--;
- } else if ( ptr[*pos].val == (int4)'!' ) {
+ }
+ else if (ptr[*pos].val == (int4) '!')
+ {
ptr[*pos].left = -1;
(*pos)--;
- findoprnd( ptr, pos );
- } else {
- ITEM *curitem = &ptr[*pos];
- int4 tmp = *pos;
+ findoprnd(ptr, pos);
+ }
+ else
+ {
+ ITEM *curitem = &ptr[*pos];
+ int4 tmp = *pos;
+
(*pos)--;
- findoprnd(ptr,pos);
+ findoprnd(ptr, pos);
curitem->left = *pos - tmp;
- findoprnd(ptr,pos);
+ findoprnd(ptr, pos);
}
}
* input
*/
Datum
-bqarr_in(PG_FUNCTION_ARGS) {
- char *buf=(char*)PG_GETARG_POINTER(0);
- WORKSTATE state;
- int4 i;
- QUERYTYPE *query;
- int4 commonlen;
- ITEM *ptr;
- NODE *tmp;
- int4 pos=0;
+bqarr_in(PG_FUNCTION_ARGS)
+{
+ char *buf = (char *) PG_GETARG_POINTER(0);
+ WORKSTATE state;
+ int4 i;
+ QUERYTYPE *query;
+ int4 commonlen;
+ ITEM *ptr;
+ NODE *tmp;
+ int4 pos = 0;
+
#ifdef BS_DEBUG
- StringInfoData pbuf;
+ StringInfoData pbuf;
#endif
state.buf = buf;
state.state = WAITOPERAND;
state.count = 0;
state.num = 0;
- state.str=NULL;
+ state.str = NULL;
/* make polish notation (postfix, but in reverse order) */
- makepol( &state );
+ makepol(&state);
if (!state.num)
- elog( ERROR,"Empty query");
+ elog(ERROR, "Empty query");
commonlen = COMPUTESIZE(state.num);
- query = (QUERYTYPE*) palloc( commonlen );
+ query = (QUERYTYPE *) palloc(commonlen);
query->len = commonlen;
query->size = state.num;
ptr = GETQUERY(query);
- for(i=state.num-1; i>=0; i-- ) {
+ for (i = state.num - 1; i >= 0; i--)
+ {
ptr[i].type = state.str->type;
ptr[i].val = state.str->val;
tmp = state.str->next;
- pfree( state.str );
+ pfree(state.str);
state.str = tmp;
}
- pos = query->size-1;
- findoprnd( ptr, &pos );
+ pos = query->size - 1;
+ findoprnd(ptr, &pos);
#ifdef BS_DEBUG
initStringInfo(&pbuf);
- for( i=0;i<query->size;i++ ) {
- if ( ptr[i].type == OPR )
+ for (i = 0; i < query->size; i++)
+ {
+ if (ptr[i].type == OPR)
appendStringInfo(&pbuf, "%c(%d) ", ptr[i].val, ptr[i].left);
else
- appendStringInfo(&pbuf, "%d ", ptr[i].val );
+ appendStringInfo(&pbuf, "%d ", ptr[i].val);
}
- elog(DEBUG3,"POR: %s", pbuf.data);
+ elog(DEBUG3, "POR: %s", pbuf.data);
pfree(pbuf.data);
#endif
- PG_RETURN_POINTER( query );
+ PG_RETURN_POINTER(query);
}
/*
* out function
*/
-typedef struct {
- ITEM *curpol;
- char *buf;
- char *cur;
- int4 buflen;
-} INFIX;
+typedef struct
+{
+ ITEM *curpol;
+ char *buf;
+ char *cur;
+ int4 buflen;
+} INFIX;
#define RESIZEBUF(inf,addsize) while( ( inf->cur - inf->buf ) + addsize + 1 >= inf->buflen ) { \
int4 len = inf->cur - inf->buf; \
}
static void
-infix(INFIX *in, bool first) {
- if ( in->curpol->type == VAL ) {
+infix(INFIX * in, bool first)
+{
+ if (in->curpol->type == VAL)
+ {
RESIZEBUF(in, 11);
- sprintf(in->cur, "%d", in->curpol->val );
- in->cur = strchr( in->cur, '\0' );
+ sprintf(in->cur, "%d", in->curpol->val);
+ in->cur = strchr(in->cur, '\0');
in->curpol--;
- } else if ( in->curpol->val == (int4)'!' ) {
- bool isopr = false;
+ }
+ else if (in->curpol->val == (int4) '!')
+ {
+ bool isopr = false;
+
RESIZEBUF(in, 1);
*(in->cur) = '!';
in->cur++;
*(in->cur) = '\0';
in->curpol--;
- if ( in->curpol->type == OPR ) {
+ if (in->curpol->type == OPR)
+ {
isopr = true;
RESIZEBUF(in, 2);
sprintf(in->cur, "( ");
- in->cur = strchr( in->cur, '\0' );
+ in->cur = strchr(in->cur, '\0');
}
- infix( in, isopr );
- if ( isopr ) {
+ infix(in, isopr);
+ if (isopr)
+ {
RESIZEBUF(in, 2);
sprintf(in->cur, " )");
- in->cur = strchr( in->cur, '\0' );
+ in->cur = strchr(in->cur, '\0');
}
- } else {
- int4 op = in->curpol->val;
- INFIX nrm;
+ }
+ else
+ {
+ int4 op = in->curpol->val;
+ INFIX nrm;
in->curpol--;
- if ( op == (int4)'|' && ! first) {
+ if (op == (int4) '|' && !first)
+ {
RESIZEBUF(in, 2);
sprintf(in->cur, "( ");
- in->cur = strchr( in->cur, '\0' );
+ in->cur = strchr(in->cur, '\0');
}
nrm.curpol = in->curpol;
nrm.buflen = 16;
- nrm.cur = nrm.buf = (char*)palloc( sizeof(char) * nrm.buflen );
+ nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
/* get right operand */
- infix( &nrm, false );
+ infix(&nrm, false);
/* get & print left operand */
in->curpol = nrm.curpol;
- infix( in, false );
+ infix(in, false);
- /* print operator & right operand*/
- RESIZEBUF(in, 3 + (nrm.cur - nrm.buf) );
+ /* print operator & right operand */
+ RESIZEBUF(in, 3 + (nrm.cur - nrm.buf));
sprintf(in->cur, " %c %s", op, nrm.buf);
- in->cur = strchr( in->cur, '\0' );
- pfree( nrm.buf );
+ in->cur = strchr(in->cur, '\0');
+ pfree(nrm.buf);
- if ( op == (int4)'|' && ! first) {
+ if (op == (int4) '|' && !first)
+ {
RESIZEBUF(in, 2);
sprintf(in->cur, " )");
- in->cur = strchr( in->cur, '\0' );
+ in->cur = strchr(in->cur, '\0');
}
}
}
Datum
-bqarr_out(PG_FUNCTION_ARGS) {
- QUERYTYPE *query = (QUERYTYPE*)PG_DETOAST_DATUM(PG_GETARG_POINTER(0));
- INFIX nrm;
+bqarr_out(PG_FUNCTION_ARGS)
+{
+ QUERYTYPE *query = (QUERYTYPE *) PG_DETOAST_DATUM(PG_GETARG_POINTER(0));
+ INFIX nrm;
- if ( query->size == 0 )
- elog(ERROR,"Empty");
+ if (query->size == 0)
+ elog(ERROR, "Empty");
nrm.curpol = GETQUERY(query) + query->size - 1;
nrm.buflen = 32;
- nrm.cur = nrm.buf = (char*)palloc( sizeof(char) * nrm.buflen );
+ nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
*(nrm.cur) = '\0';
- infix( &nrm, true );
+ infix(&nrm, true);
- PG_FREE_IF_COPY(query,0);
- PG_RETURN_POINTER( nrm.buf );
+ PG_FREE_IF_COPY(query, 0);
+ PG_RETURN_POINTER(nrm.buf);
}
static int4
-countdroptree( ITEM *q, int4 pos ) {
- if ( q[pos].type == VAL ) {
+countdroptree(ITEM * q, int4 pos)
+{
+ if (q[pos].type == VAL)
return 1;
- } else if ( q[pos].val == (int4)'!' ) {
- return 1+countdroptree(q, pos-1);
- } else {
- return 1 + countdroptree(q, pos-1) + countdroptree(q, pos + q[pos].left);
- }
+ else if (q[pos].val == (int4) '!')
+ return 1 + countdroptree(q, pos - 1);
+ else
+ return 1 + countdroptree(q, pos - 1) + countdroptree(q, pos + q[pos].left);
}
/*
* we can modify query tree for clearing
*/
static int4
-shorterquery( ITEM *q, int4 len ) {
- int4 index,posnot,poscor;
- bool notisleft = false;
- int4 drop,i;
+shorterquery(ITEM * q, int4 len)
+{
+ int4 index,
+ posnot,
+ poscor;
+ bool notisleft = false;
+ int4 drop,
+ i;
/* out all '!' */
- do {
- index=0;
- drop=0;
+ do
+ {
+ index = 0;
+ drop = 0;
/* find ! */
- for(posnot=0; posnot < len; posnot++)
- if ( q[posnot].type == OPR && q[posnot].val == (int4)'!') {
- index=1;
+ for (posnot = 0; posnot < len; posnot++)
+ if (q[posnot].type == OPR && q[posnot].val == (int4) '!')
+ {
+ index = 1;
break;
}
- if ( posnot == len )
+ if (posnot == len)
return len;
/* last operator is ! */
- if ( posnot == len-1 )
+ if (posnot == len - 1)
return 0;
/* find operator for this operand */
- for( poscor=posnot+1; poscor<len; poscor++) {
- if ( q[poscor].type == OPR ) {
- if ( poscor == posnot+1 ) {
+ for (poscor = posnot + 1; poscor < len; poscor++)
+ {
+ if (q[poscor].type == OPR)
+ {
+ if (poscor == posnot + 1)
+ {
notisleft = false;
break;
- } else if ( q[poscor].left + poscor == posnot ) {
+ }
+ else if (q[poscor].left + poscor == posnot)
+ {
notisleft = true;
break;
}
}
}
- if ( q[poscor].val == (int4)'!' ) {
+ if (q[poscor].val == (int4) '!')
+ {
drop = countdroptree(q, poscor);
- q[poscor-1].type=VAL;
- for(i=poscor+1;i<len;i++)
- if ( q[i].type == OPR && q[i].left + i <= poscor )
+ q[poscor - 1].type = VAL;
+ for (i = poscor + 1; i < len; i++)
+ if (q[i].type == OPR && q[i].left + i <= poscor)
q[i].left += drop - 2;
- memcpy( (void*)&q[poscor-drop+1],
- (void*)&q[poscor-1],
- sizeof(ITEM) * ( len - (poscor-1) ));
+ memcpy((void *) &q[poscor - drop + 1],
+ (void *) &q[poscor - 1],
+ sizeof(ITEM) * (len - (poscor - 1)));
len -= drop - 2;
- } else if ( q[poscor].val == (int4)'|' ) {
+ }
+ else if (q[poscor].val == (int4) '|')
+ {
drop = countdroptree(q, poscor);
- q[poscor-1].type=VAL;
- q[poscor].val=(int4)'!';
- q[poscor].left=-1;
- for(i=poscor+1;i<len;i++)
- if ( q[i].type == OPR && q[i].left + i < poscor )
+ q[poscor - 1].type = VAL;
+ q[poscor].val = (int4) '!';
+ q[poscor].left = -1;
+ for (i = poscor + 1; i < len; i++)
+ if (q[i].type == OPR && q[i].left + i < poscor)
q[i].left += drop - 2;
- memcpy( (void*)&q[poscor-drop+1],
- (void*)&q[poscor-1],
- sizeof(ITEM) * ( len - (poscor-1) ));
+ memcpy((void *) &q[poscor - drop + 1],
+ (void *) &q[poscor - 1],
+ sizeof(ITEM) * (len - (poscor - 1)));
len -= drop - 2;
- } else { /* &-operator */
+ }
+ else
+ { /* &-operator */
if (
- (notisleft && q[poscor-1].type == OPR &&
- q[poscor-1].val == (int4)'!' ) ||
- (!notisleft && q[poscor+q[poscor].left].type == OPR &&
- q[poscor+q[poscor].left].val == (int4)'!' )
- ) { /* drop subtree */
+ (notisleft && q[poscor - 1].type == OPR &&
+ q[poscor - 1].val == (int4) '!') ||
+ (!notisleft && q[poscor + q[poscor].left].type == OPR &&
+ q[poscor + q[poscor].left].val == (int4) '!')
+ )
+ { /* drop subtree */
drop = countdroptree(q, poscor);
- q[poscor-1].type=VAL;
- q[poscor].val=(int4)'!';
- q[poscor].left=-1;
- for(i=poscor+1;i<len;i++)
- if ( q[i].type == OPR && q[i].left + i < poscor )
+ q[poscor - 1].type = VAL;
+ q[poscor].val = (int4) '!';
+ q[poscor].left = -1;
+ for (i = poscor + 1; i < len; i++)
+ if (q[i].type == OPR && q[i].left + i < poscor)
q[i].left += drop - 2;
- memcpy( (void*)&q[poscor-drop+1],
- (void*)&q[poscor-1],
- sizeof(ITEM) * ( len - (poscor-1) ));
+ memcpy((void *) &q[poscor - drop + 1],
+ (void *) &q[poscor - 1],
+ sizeof(ITEM) * (len - (poscor - 1)));
len -= drop - 2;
- } else { /* drop only operator */
- int4 subtreepos = ( notisleft ) ?
- poscor-1 : poscor+q[poscor].left;
- int4 subtreelen = countdroptree( q, subtreepos );
+ }
+ else
+ { /* drop only operator */
+ int4 subtreepos = (notisleft) ?
+ poscor - 1 : poscor + q[poscor].left;
+ int4 subtreelen = countdroptree(q, subtreepos);
+
drop = countdroptree(q, poscor);
- for(i=poscor+1;i<len;i++)
- if ( q[i].type == OPR && q[i].left + i < poscor )
+ for (i = poscor + 1; i < len; i++)
+ if (q[i].type == OPR && q[i].left + i < poscor)
q[i].left += drop - subtreelen;
- memcpy( (void*)&q[ subtreepos+1 ],
- (void*)&q[poscor+1],
- sizeof(ITEM)*( len - (poscor-1) ) );
- memcpy( (void*)&q[ poscor-drop+1 ],
- (void*)&q[subtreepos-subtreelen+1],
- sizeof(ITEM)*( len - (drop-subtreelen) ) );
+ memcpy((void *) &q[subtreepos + 1],
+ (void *) &q[poscor + 1],
+ sizeof(ITEM) * (len - (poscor - 1)));
+ memcpy((void *) &q[poscor - drop + 1],
+ (void *) &q[subtreepos - subtreelen + 1],
+ sizeof(ITEM) * (len - (drop - subtreelen)));
len -= drop - subtreelen;
}
}
- } while( index );
+ } while (index);
return len;
}
Datum
-querytree(PG_FUNCTION_ARGS) {
- QUERYTYPE *query = (QUERYTYPE*)PG_DETOAST_DATUM(PG_GETARG_POINTER(0));
- INFIX nrm;
- text *res;
- ITEM *q;
- int4 len;
-
- if ( query->size == 0 )
- elog(ERROR,"Empty");
-
- q = (ITEM*)palloc( sizeof(ITEM) * query->size );
- memcpy( (void*)q, GETQUERY(query), sizeof(ITEM) * query->size );
- len = shorterquery( q, query->size );
- PG_FREE_IF_COPY(query,0);
-
- if ( len == 0 ) {
- res = (text*) palloc( 1 + VARHDRSZ );
+querytree(PG_FUNCTION_ARGS)
+{
+ QUERYTYPE *query = (QUERYTYPE *) PG_DETOAST_DATUM(PG_GETARG_POINTER(0));
+ INFIX nrm;
+ text *res;
+ ITEM *q;
+ int4 len;
+
+ if (query->size == 0)
+ elog(ERROR, "Empty");
+
+ q = (ITEM *) palloc(sizeof(ITEM) * query->size);
+ memcpy((void *) q, GETQUERY(query), sizeof(ITEM) * query->size);
+ len = shorterquery(q, query->size);
+ PG_FREE_IF_COPY(query, 0);
+
+ if (len == 0)
+ {
+ res = (text *) palloc(1 + VARHDRSZ);
VARATT_SIZEP(res) = 1 + VARHDRSZ;
- *((char*)VARDATA(res)) = 'T';
- } else {
+ *((char *) VARDATA(res)) = 'T';
+ }
+ else
+ {
nrm.curpol = q + len - 1;
nrm.buflen = 32;
- nrm.cur = nrm.buf = (char*)palloc( sizeof(char) * nrm.buflen );
+ nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
*(nrm.cur) = '\0';
- infix( &nrm, true );
+ infix(&nrm, true);
- res = (text*) palloc( nrm.cur-nrm.buf + VARHDRSZ );
- VARATT_SIZEP(res) = nrm.cur-nrm.buf + VARHDRSZ;
- strncpy( VARDATA(res), nrm.buf, nrm.cur-nrm.buf );
+ res = (text *) palloc(nrm.cur - nrm.buf + VARHDRSZ);
+ VARATT_SIZEP(res) = nrm.cur - nrm.buf + VARHDRSZ;
+ strncpy(VARDATA(res), nrm.buf, nrm.cur - nrm.buf);
}
pfree(q);
- PG_RETURN_POINTER( res );
+ PG_RETURN_POINTER(res);
}
/*
static ArrayType *intarray_concat_arrays(ArrayType *a, ArrayType *b);
static ArrayType *int_to_intset(int32 elem);
-PG_FUNCTION_INFO_V1( intset );
-PG_FUNCTION_INFO_V1( icount );
-PG_FUNCTION_INFO_V1( sort );
-PG_FUNCTION_INFO_V1( sort_asc );
-PG_FUNCTION_INFO_V1( sort_desc );
-PG_FUNCTION_INFO_V1( uniq );
-PG_FUNCTION_INFO_V1( idx );
-PG_FUNCTION_INFO_V1( subarray );
-PG_FUNCTION_INFO_V1( intarray_push_elem );
-PG_FUNCTION_INFO_V1( intarray_push_array );
-PG_FUNCTION_INFO_V1( intarray_del_elem );
-PG_FUNCTION_INFO_V1( intset_union_elem );
-PG_FUNCTION_INFO_V1( intset_subtract );
-Datum intset(PG_FUNCTION_ARGS);
-Datum icount(PG_FUNCTION_ARGS);
-Datum sort(PG_FUNCTION_ARGS);
-Datum sort_asc(PG_FUNCTION_ARGS);
-Datum sort_desc(PG_FUNCTION_ARGS);
-Datum uniq(PG_FUNCTION_ARGS);
-Datum idx(PG_FUNCTION_ARGS);
-Datum subarray(PG_FUNCTION_ARGS);
-Datum intarray_push_elem(PG_FUNCTION_ARGS);
-Datum intarray_push_array(PG_FUNCTION_ARGS);
-Datum intarray_del_elem(PG_FUNCTION_ARGS);
-Datum intset_union_elem(PG_FUNCTION_ARGS);
-Datum intset_subtract(PG_FUNCTION_ARGS);
+PG_FUNCTION_INFO_V1(intset);
+PG_FUNCTION_INFO_V1(icount);
+PG_FUNCTION_INFO_V1(sort);
+PG_FUNCTION_INFO_V1(sort_asc);
+PG_FUNCTION_INFO_V1(sort_desc);
+PG_FUNCTION_INFO_V1(uniq);
+PG_FUNCTION_INFO_V1(idx);
+PG_FUNCTION_INFO_V1(subarray);
+PG_FUNCTION_INFO_V1(intarray_push_elem);
+PG_FUNCTION_INFO_V1(intarray_push_array);
+PG_FUNCTION_INFO_V1(intarray_del_elem);
+PG_FUNCTION_INFO_V1(intset_union_elem);
+PG_FUNCTION_INFO_V1(intset_subtract);
+Datum intset(PG_FUNCTION_ARGS);
+Datum icount(PG_FUNCTION_ARGS);
+Datum sort(PG_FUNCTION_ARGS);
+Datum sort_asc(PG_FUNCTION_ARGS);
+Datum sort_desc(PG_FUNCTION_ARGS);
+Datum uniq(PG_FUNCTION_ARGS);
+Datum idx(PG_FUNCTION_ARGS);
+Datum subarray(PG_FUNCTION_ARGS);
+Datum intarray_push_elem(PG_FUNCTION_ARGS);
+Datum intarray_push_array(PG_FUNCTION_ARGS);
+Datum intarray_del_elem(PG_FUNCTION_ARGS);
+Datum intset_union_elem(PG_FUNCTION_ARGS);
+Datum intset_subtract(PG_FUNCTION_ARGS);
static int32
-intarray_match_first(ArrayType *a, int32 elem) {
- int32 *aa, c, i;
- c = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+intarray_match_first(ArrayType *a, int32 elem)
+{
+ int32 *aa,
+ c,
+ i;
+
+ c = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
aa = ARRPTR(a);
for (i = 0; i < c; i++)
- if (aa[i] == elem) return (i + 1);
+ if (aa[i] == elem)
+ return (i + 1);
return 0;
}
static ArrayType *
-intarray_add_elem(ArrayType *a, int32 elem) {
- ArrayType *result;
- int32 *r;
- int32 c = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+intarray_add_elem(ArrayType *a, int32 elem)
+{
+ ArrayType *result;
+ int32 *r;
+ int32 c = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+
result = new_intArrayType(c + 1);
r = ARRPTR(result);
- if (c > 0) memcpy(r, ARRPTR(a), c * sizeof(int32));
+ if (c > 0)
+ memcpy(r, ARRPTR(a), c * sizeof(int32));
r[c] = elem;
return result;
}
static ArrayType *
-intarray_concat_arrays(ArrayType *a, ArrayType *b) {
- ArrayType *result;
- int32 ac = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
- int32 bc = (ARRISVOID(b)) ? 0 : ARRNELEMS(b);
- result = new_intArrayType(ac+bc);
- if ( ac )
+intarray_concat_arrays(ArrayType *a, ArrayType *b)
+{
+ ArrayType *result;
+ int32 ac = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+ int32 bc = (ARRISVOID(b)) ? 0 : ARRNELEMS(b);
+
+ result = new_intArrayType(ac + bc);
+ if (ac)
memcpy(ARRPTR(result), ARRPTR(a), ac * sizeof(int32));
- if ( bc )
+ if (bc)
memcpy(ARRPTR(result) + ac, ARRPTR(b), bc * sizeof(int32));
return result;
}
static ArrayType *
-int_to_intset(int32 n) {
- ArrayType *result;
- int32 *aa;
+int_to_intset(int32 n)
+{
+ ArrayType *result;
+ int32 *aa;
+
result = new_intArrayType(1);
aa = ARRPTR(result);
aa[0] = n;
}
static int
-compASC(const void *a, const void *b) {
- if ( *(int4*)a == *(int4*)b ) return 0;
- return ( *(int4*)a > *(int4*)b ) ? 1 : -1;
+compASC(const void *a, const void *b)
+{
+ if (*(int4 *) a == *(int4 *) b)
+ return 0;
+ return (*(int4 *) a > *(int4 *) b) ? 1 : -1;
}
static int
-compDESC(const void *a, const void *b) {
- if ( *(int4*)a == *(int4*)b ) return 0;
- return ( *(int4*)a < *(int4*)b ) ? 1 : -1;
+compDESC(const void *a, const void *b)
+{
+ if (*(int4 *) a == *(int4 *) b)
+ return 0;
+ return (*(int4 *) a < *(int4 *) b) ? 1 : -1;
}
-#define QSORT(a, direction) \
+#define QSORT(a, direction) \
if (ARRNELEMS(a) > 1) \
- qsort((void*)ARRPTR(a), ARRNELEMS(a),sizeof(int4), \
+ qsort((void*)ARRPTR(a), ARRNELEMS(a),sizeof(int4), \
(direction) ? compASC : compDESC )
#define UNIX_UNIQ(a) a = resize_intArrayType(a, unix_uniq(ARRPTR(a), ARRNELEMS(a)))
static int32
-unix_uniq(int32 *array, int32 count) {
- register int32 i, k = 0;
+unix_uniq(int32 *array, int32 count)
+{
+ register int32 i,
+ k = 0;
+
for (i = 1; i < count; i++)
- if (array[k] != array[i]) {
+ if (array[k] != array[i])
+ {
k++;
- if (i > k) array[k] = array[i];
+ if (i > k)
+ array[k] = array[i];
}
- return (k+1);
+ return (k + 1);
}
Datum
-intset(PG_FUNCTION_ARGS) {
- PG_RETURN_POINTER(int_to_intset(PG_GETARG_INT32(0)));
+intset(PG_FUNCTION_ARGS)
+{
+ PG_RETURN_POINTER(int_to_intset(PG_GETARG_INT32(0)));
}
Datum
-icount(PG_FUNCTION_ARGS) {
- ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
- int32 count = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+icount(PG_FUNCTION_ARGS)
+{
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
+ int32 count = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+
PG_FREE_IF_COPY(a, 0);
PG_RETURN_INT32(count);
}
Datum
-sort(PG_FUNCTION_ARGS) {
- ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
- text *dirstr = ( fcinfo->nargs==2 ) ? PG_GETARG_TEXT_P(1) : NULL;
- int32 dc = ( dirstr ) ? VARSIZE(dirstr)-VARHDRSZ : 0;
- char *d = ( dirstr ) ? VARDATA(dirstr) : NULL;
- int dir = -1;
- if (ARRISVOID(a) || ARRNELEMS(a) < 2) PG_RETURN_POINTER(a);
-
- if (dirstr==NULL || (dc == 3
- && (d[0] == 'A' || d[0] == 'a')
- && (d[1] == 'S' || d[1] == 's')
- && (d[2] == 'C' || d[2] == 'c')))
+sort(PG_FUNCTION_ARGS)
+{
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+ text *dirstr = (fcinfo->nargs == 2) ? PG_GETARG_TEXT_P(1) : NULL;
+ int32 dc = (dirstr) ? VARSIZE(dirstr) - VARHDRSZ : 0;
+ char *d = (dirstr) ? VARDATA(dirstr) : NULL;
+ int dir = -1;
+
+ if (ARRISVOID(a) || ARRNELEMS(a) < 2)
+ PG_RETURN_POINTER(a);
+
+ if (dirstr == NULL || (dc == 3
+ && (d[0] == 'A' || d[0] == 'a')
+ && (d[1] == 'S' || d[1] == 's')
+ && (d[2] == 'C' || d[2] == 'c')))
dir = 1;
else if (dc == 4
- && (d[0] == 'D' || d[0] == 'd')
- && (d[1] == 'E' || d[1] == 'e')
- && (d[2] == 'S' || d[2] == 's')
- && (d[3] == 'C' || d[3] == 'c'))
+ && (d[0] == 'D' || d[0] == 'd')
+ && (d[1] == 'E' || d[1] == 'e')
+ && (d[2] == 'S' || d[2] == 's')
+ && (d[3] == 'C' || d[3] == 'c'))
dir = 0;
if (dir == -1)
elog(ERROR, "Invalid second parameter in function sort. It must be 'ASC' or 'DESC'.");
}
Datum
-sort_asc(PG_FUNCTION_ARGS) {
- ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
- if (ARRISVOID(a)) PG_RETURN_POINTER(a);
+sort_asc(PG_FUNCTION_ARGS)
+{
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+
+ if (ARRISVOID(a))
+ PG_RETURN_POINTER(a);
QSORT(a, 1);
PG_RETURN_POINTER(a);
}
Datum
-sort_desc(PG_FUNCTION_ARGS) {
- ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
- if (ARRISVOID(a)) PG_RETURN_POINTER(a);
+sort_desc(PG_FUNCTION_ARGS)
+{
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+
+ if (ARRISVOID(a))
+ PG_RETURN_POINTER(a);
QSORT(a, 0);
PG_RETURN_POINTER(a);
}
Datum
-uniq(PG_FUNCTION_ARGS) {
- ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
- if (ARRISVOID(a) || ARRNELEMS(a) < 2) PG_RETURN_POINTER(a);
+uniq(PG_FUNCTION_ARGS)
+{
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+
+ if (ARRISVOID(a) || ARRNELEMS(a) < 2)
+ PG_RETURN_POINTER(a);
UNIX_UNIQ(a);
PG_RETURN_POINTER(a);
}
Datum
-idx(PG_FUNCTION_ARGS) {
- ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
- int32 result = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
- if (result) result = intarray_match_first(a, PG_GETARG_INT32(1));
+idx(PG_FUNCTION_ARGS)
+{
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
+ int32 result = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+
+ if (result)
+ result = intarray_match_first(a, PG_GETARG_INT32(1));
PG_FREE_IF_COPY(a, 0);
PG_RETURN_INT32(result);
}
Datum
-subarray(PG_FUNCTION_ARGS) {
- ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
- ArrayType *result;
- int32 start = ( PG_GETARG_INT32(1) > 0 ) ? PG_GETARG_INT32(1)-1 : PG_GETARG_INT32(1);
- int32 len = ( fcinfo->nargs==3 ) ? PG_GETARG_INT32(2) : 0;
- int32 end = 0;
- int32 c;
-
- if ( ARRISVOID(a) ) {
+subarray(PG_FUNCTION_ARGS)
+{
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
+ ArrayType *result;
+ int32 start = (PG_GETARG_INT32(1) > 0) ? PG_GETARG_INT32(1) - 1 : PG_GETARG_INT32(1);
+ int32 len = (fcinfo->nargs == 3) ? PG_GETARG_INT32(2) : 0;
+ int32 end = 0;
+ int32 c;
+
+ if (ARRISVOID(a))
+ {
PG_FREE_IF_COPY(a, 0);
- PG_RETURN_POINTER( new_intArrayType(0) );
+ PG_RETURN_POINTER(new_intArrayType(0));
}
c = ARRNELEMS(a);
-
- if ( start < 0 )
+
+ if (start < 0)
start = c + start;
- if ( len < 0 )
+ if (len < 0)
end = c + len;
- else if ( len == 0 )
+ else if (len == 0)
end = c;
else
end = start + len;
- if ( end > c )
- end = c;
+ if (end > c)
+ end = c;
- if ( start < 0 )
+ if (start < 0)
start = 0;
- if ( start >= end || end <= 0 ) {
+ if (start >= end || end <= 0)
+ {
PG_FREE_IF_COPY(a, 0);
- PG_RETURN_POINTER( new_intArrayType(0) );
+ PG_RETURN_POINTER(new_intArrayType(0));
}
- result = new_intArrayType(end-start);
- if (end-start > 0)
- memcpy(ARRPTR(result), ARRPTR(a) + start, (end-start) * sizeof(int32));
+ result = new_intArrayType(end - start);
+ if (end - start > 0)
+ memcpy(ARRPTR(result), ARRPTR(a) + start, (end - start) * sizeof(int32));
PG_FREE_IF_COPY(a, 0);
PG_RETURN_POINTER(result);
}
Datum
-intarray_push_elem(PG_FUNCTION_ARGS) {
- ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
- ArrayType *result;
+intarray_push_elem(PG_FUNCTION_ARGS)
+{
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
+ ArrayType *result;
+
result = intarray_add_elem(a, PG_GETARG_INT32(1));
PG_FREE_IF_COPY(a, 0);
PG_RETURN_POINTER(result);
}
Datum
-intarray_push_array(PG_FUNCTION_ARGS) {
- ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
- ArrayType *b = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(1)));
- ArrayType *result;
+intarray_push_array(PG_FUNCTION_ARGS)
+{
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
+ ArrayType *b = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(1)));
+ ArrayType *result;
+
result = intarray_concat_arrays(a, b);
PG_FREE_IF_COPY(a, 0);
PG_FREE_IF_COPY(b, 1);
}
Datum
-intarray_del_elem(PG_FUNCTION_ARGS) {
- ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
- int32 c = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
- int32 *aa = ARRPTR(a);
- int32 n = 0, i;
- int32 elem = PG_GETARG_INT32(1);
+intarray_del_elem(PG_FUNCTION_ARGS)
+{
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+ int32 c = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+ int32 *aa = ARRPTR(a);
+ int32 n = 0,
+ i;
+ int32 elem = PG_GETARG_INT32(1);
+
for (i = 0; i < c; i++)
- if (aa[i] != elem) {
- if (i > n) aa[n++] = aa[i];
- else n++;
+ if (aa[i] != elem)
+ {
+ if (i > n)
+ aa[n++] = aa[i];
+ else
+ n++;
}
- if (c > 0) a = resize_intArrayType(a, n);
+ if (c > 0)
+ a = resize_intArrayType(a, n);
PG_RETURN_POINTER(a);
}
Datum
-intset_union_elem(PG_FUNCTION_ARGS) {
- ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
- ArrayType *result;
+intset_union_elem(PG_FUNCTION_ARGS)
+{
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
+ ArrayType *result;
+
result = intarray_add_elem(a, PG_GETARG_INT32(1));
PG_FREE_IF_COPY(a, 0);
QSORT(result, 1);
}
Datum
-intset_subtract(PG_FUNCTION_ARGS) {
- ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
- ArrayType *b = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
- ArrayType *result;
- int32 ca = ARRISVOID(a);
- int32 cb = ARRISVOID(b);
- int32 *aa, *bb, *r;
- int32 n = 0, i = 0, k = 0;
- QSORT(a, 1); UNIX_UNIQ(a); ca = ARRNELEMS(a);
- QSORT(b, 1); UNIX_UNIQ(b); cb = ARRNELEMS(b);
+intset_subtract(PG_FUNCTION_ARGS)
+{
+ ArrayType *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+ ArrayType *b = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
+ ArrayType *result;
+ int32 ca = ARRISVOID(a);
+ int32 cb = ARRISVOID(b);
+ int32 *aa,
+ *bb,
+ *r;
+ int32 n = 0,
+ i = 0,
+ k = 0;
+
+ QSORT(a, 1);
+ UNIX_UNIQ(a);
+ ca = ARRNELEMS(a);
+ QSORT(b, 1);
+ UNIX_UNIQ(b);
+ cb = ARRNELEMS(b);
result = new_intArrayType(ca);
aa = ARRPTR(a);
bb = ARRPTR(b);
r = ARRPTR(result);
- while (i < ca) {
- if (k == cb || aa[i] < bb[k]) r[n++] = aa[i++];
- else if (aa[i] == bb[k]) { i++; k++; }
- else k++;
+ while (i < ca)
+ {
+ if (k == cb || aa[i] < bb[k])
+ r[n++] = aa[i++];
+ else if (aa[i] == bb[k])
+ {
+ i++;
+ k++;
+ }
+ else
+ k++;
}
result = resize_intArrayType(result, n);
- pfree(a); pfree(b);
+ pfree(a);
+ pfree(b);
PG_RETURN_POINTER(result);
}
-
/*
- * GiST support for ltree[]
+ * GiST support for ltree[]
* Teodor Sigaev <teodor@stack.net>
*/
#include "crc32.h"
-PG_FUNCTION_INFO_V1( _ltree_compress );
-Datum _ltree_compress(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( _ltree_same );
-Datum _ltree_same(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( _ltree_union );
-Datum _ltree_union(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( _ltree_penalty );
-Datum _ltree_penalty(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( _ltree_picksplit );
-Datum _ltree_picksplit(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( _ltree_consistent );
-Datum _ltree_consistent(PG_FUNCTION_ARGS);
+PG_FUNCTION_INFO_V1(_ltree_compress);
+Datum _ltree_compress(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(_ltree_same);
+Datum _ltree_same(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(_ltree_union);
+Datum _ltree_union(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(_ltree_penalty);
+Datum _ltree_penalty(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(_ltree_picksplit);
+Datum _ltree_picksplit(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(_ltree_consistent);
+Datum _ltree_consistent(PG_FUNCTION_ARGS);
#define GETENTRY(vec,pos) ((ltree_gist *) DatumGetPointer(((GISTENTRY *) VARDATA(vec))[(pos)].key))
#define NEXTVAL(x) ( (ltree*)( (char*)(x) + INTALIGN( VARSIZE(x) ) ) )
-#define SUMBIT(val) ( \
+#define SUMBIT(val) ( \
GETBITBYTE(val,0) + \
GETBITBYTE(val,1) + \
GETBITBYTE(val,2) + \
GETBITBYTE(val,4) + \
GETBITBYTE(val,5) + \
GETBITBYTE(val,6) + \
- GETBITBYTE(val,7) \
+ GETBITBYTE(val,7) \
)
#define WISH_F(a,b,c) (double)( -(double)(((a)-(b))*((a)-(b))*((a)-(b)))*(c) )
static void
-hashing(BITVECP sign, ltree *t) {
- int tlen = t->numlevel;
+hashing(BITVECP sign, ltree * t)
+{
+ int tlen = t->numlevel;
ltree_level *cur = LTREE_FIRST(t);
- int hash;
+ int hash;
- while(tlen > 0) {
- hash = ltree_crc32_sz( cur->name, cur->len );
- AHASH( sign, hash );
+ while (tlen > 0)
+ {
+ hash = ltree_crc32_sz(cur->name, cur->len);
+ AHASH(sign, hash);
cur = LEVEL_NEXT(cur);
tlen--;
}
}
-Datum
-_ltree_compress(PG_FUNCTION_ARGS) {
- GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
+Datum
+_ltree_compress(PG_FUNCTION_ARGS)
+{
+ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
GISTENTRY *retval = entry;
- if ( entry->leafkey ) { /* ltree */
- ltree_gist *key;
- ArrayType *val = DatumGetArrayTypeP(entry->key);
- int4 len = LTG_HDRSIZE + ASIGLEN;
- int num=ArrayGetNItems( ARR_NDIM(val), ARR_DIMS(val) );
- ltree *item = (ltree*)ARR_DATA_PTR(val);
+ if (entry->leafkey)
+ { /* ltree */
+ ltree_gist *key;
+ ArrayType *val = DatumGetArrayTypeP(entry->key);
+ int4 len = LTG_HDRSIZE + ASIGLEN;
+ int num = ArrayGetNItems(ARR_NDIM(val), ARR_DIMS(val));
+ ltree *item = (ltree *) ARR_DATA_PTR(val);
- if ( ARR_NDIM(val) != 1 )
- elog(ERROR,"Dimension of array != 1");
+ if (ARR_NDIM(val) != 1)
+ elog(ERROR, "Dimension of array != 1");
- key = (ltree_gist*)palloc( len );
+ key = (ltree_gist *) palloc(len);
key->len = len;
key->flag = 0;
- MemSet( LTG_SIGN(key), 0, sizeof(ASIGLEN) );
- while( num>0 ) {
+ MemSet(LTG_SIGN(key), 0, sizeof(ASIGLEN));
+ while (num > 0)
+ {
hashing(LTG_SIGN(key), item);
num--;
item = NEXTVAL(item);
}
- if ( PointerGetDatum(val) != entry->key )
+ if (PointerGetDatum(val) != entry->key)
pfree(val);
- retval = (GISTENTRY*)palloc( sizeof(GISTENTRY) );
+ retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
gistentryinit(*retval, PointerGetDatum(key),
- entry->rel, entry->page,
- entry->offset, key->len, FALSE);
- } else {
- int4 i,len;
- ltree_gist *key;
+ entry->rel, entry->page,
+ entry->offset, key->len, FALSE);
+ }
+ else
+ {
+ int4 i,
+ len;
+ ltree_gist *key;
- BITVECP sign = LTG_SIGN(DatumGetPointer( entry->key ) );
+ BITVECP sign = LTG_SIGN(DatumGetPointer(entry->key));
ALOOPBYTE(
- if ( sign[i] != 0xff )
- PG_RETURN_POINTER(retval);
+ if (sign[i] != 0xff)
+ PG_RETURN_POINTER(retval);
);
- len = LTG_HDRSIZE;
- key = (ltree_gist*)palloc( len );
+ len = LTG_HDRSIZE;
+ key = (ltree_gist *) palloc(len);
key->len = len;
key->flag = LTG_ALLTRUE;
- retval = (GISTENTRY*)palloc( sizeof(GISTENTRY) );
+ retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
gistentryinit(*retval, PointerGetDatum(key),
- entry->rel, entry->page,
- entry->offset, key->len, FALSE);
+ entry->rel, entry->page,
+ entry->offset, key->len, FALSE);
}
PG_RETURN_POINTER(retval);
}
-Datum
-_ltree_same(PG_FUNCTION_ARGS) {
- ltree_gist* a=(ltree_gist*)PG_GETARG_POINTER(0);
- ltree_gist* b=(ltree_gist*)PG_GETARG_POINTER(1);
- bool *result = (bool *)PG_GETARG_POINTER(2);
+Datum
+_ltree_same(PG_FUNCTION_ARGS)
+{
+ ltree_gist *a = (ltree_gist *) PG_GETARG_POINTER(0);
+ ltree_gist *b = (ltree_gist *) PG_GETARG_POINTER(1);
+ bool *result = (bool *) PG_GETARG_POINTER(2);
- if ( LTG_ISALLTRUE(a) && LTG_ISALLTRUE(b) ) {
+ if (LTG_ISALLTRUE(a) && LTG_ISALLTRUE(b))
*result = true;
- } else if ( LTG_ISALLTRUE(a) ) {
+ else if (LTG_ISALLTRUE(a))
*result = false;
- } else if ( LTG_ISALLTRUE(b) ) {
+ else if (LTG_ISALLTRUE(b))
*result = false;
- } else {
- int4 i;
- BITVECP sa=LTG_SIGN(a), sb=LTG_SIGN(b);
+ else
+ {
+ int4 i;
+ BITVECP sa = LTG_SIGN(a),
+ sb = LTG_SIGN(b);
+
*result = true;
ALOOPBYTE(
- if ( sa[i] != sb[i] ) {
- *result = false;
- break;
- }
+ if (sa[i] != sb[i])
+ {
+ *result = false;
+ break;
+ }
);
- }
- PG_RETURN_POINTER(result);
+ }
+ PG_RETURN_POINTER(result);
}
-static int4
-unionkey( BITVECP sbase, ltree_gist *add ) {
- int4 i;
- BITVECP sadd = LTG_SIGN( add );
+static int4
+unionkey(BITVECP sbase, ltree_gist * add)
+{
+ int4 i;
+ BITVECP sadd = LTG_SIGN(add);
- if ( LTG_ISALLTRUE(add) )
+ if (LTG_ISALLTRUE(add))
return 1;
ALOOPBYTE(
- sbase[i] |= sadd[i];
+ sbase[i] |= sadd[i];
);
return 0;
}
-Datum
-_ltree_union(PG_FUNCTION_ARGS) {
- bytea *entryvec = (bytea *) PG_GETARG_POINTER(0);
- int *size = (int *) PG_GETARG_POINTER(1);
- ABITVEC base;
- int4 len = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY);
- int4 i;
- int4 flag = 0;
- ltree_gist *result;
-
- MemSet( (void*)base, 0, sizeof(ABITVEC) );
- for(i=0;i<len;i++) {
- if ( unionkey( base, GETENTRY(entryvec, i) ) ) {
+Datum
+_ltree_union(PG_FUNCTION_ARGS)
+{
+ bytea *entryvec = (bytea *) PG_GETARG_POINTER(0);
+ int *size = (int *) PG_GETARG_POINTER(1);
+ ABITVEC base;
+ int4 len = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY);
+ int4 i;
+ int4 flag = 0;
+ ltree_gist *result;
+
+ MemSet((void *) base, 0, sizeof(ABITVEC));
+ for (i = 0; i < len; i++)
+ {
+ if (unionkey(base, GETENTRY(entryvec, i)))
+ {
flag = LTG_ALLTRUE;
break;
}
}
- len = LTG_HDRSIZE + ( ( flag & LTG_ALLTRUE ) ? 0 : ASIGLEN );
- result = (ltree_gist*)palloc( len );
+ len = LTG_HDRSIZE + ((flag & LTG_ALLTRUE) ? 0 : ASIGLEN);
+ result = (ltree_gist *) palloc(len);
*size = result->len = len;
result->flag = flag;
- if ( ! LTG_ISALLTRUE(result) )
- memcpy((void*)LTG_SIGN(result), (void*)base, sizeof( ABITVEC ) );
+ if (!LTG_ISALLTRUE(result))
+ memcpy((void *) LTG_SIGN(result), (void *) base, sizeof(ABITVEC));
- PG_RETURN_POINTER(result);
+ PG_RETURN_POINTER(result);
}
static int4
-sizebitvec( BITVECP sign ) {
- int4 size=0, i;
+sizebitvec(BITVECP sign)
+{
+ int4 size = 0,
+ i;
+
ALOOPBYTE(
- size += SUMBIT(*(char*)sign);
- sign = (BITVECP) ( ((char*)sign) + 1 );
+ size += SUMBIT(*(char *) sign);
+ sign = (BITVECP) (((char *) sign) + 1);
);
return size;
}
-Datum
-_ltree_penalty(PG_FUNCTION_ARGS) {
- ltree_gist *origval = (ltree_gist*)DatumGetPointer( ( (GISTENTRY *)PG_GETARG_POINTER(0) )->key );
- ltree_gist *newval = (ltree_gist*)DatumGetPointer( ( (GISTENTRY *)PG_GETARG_POINTER(1) )->key );
- float *penalty = (float *) PG_GETARG_POINTER(2);
- BITVECP orig = LTG_SIGN(origval);
+Datum
+_ltree_penalty(PG_FUNCTION_ARGS)
+{
+ ltree_gist *origval = (ltree_gist *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(0))->key);
+ ltree_gist *newval = (ltree_gist *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(1))->key);
+ float *penalty = (float *) PG_GETARG_POINTER(2);
+ BITVECP orig = LTG_SIGN(origval);
- if ( LTG_ISALLTRUE(origval) ) {
+ if (LTG_ISALLTRUE(origval))
+ {
*penalty = 0.0;
- PG_RETURN_POINTER( penalty );
+ PG_RETURN_POINTER(penalty);
}
- if ( LTG_ISALLTRUE(newval) ) {
- *penalty = (float) (ASIGLENBIT - sizebitvec( orig ) );
- } else {
+ if (LTG_ISALLTRUE(newval))
+ *penalty = (float) (ASIGLENBIT - sizebitvec(orig));
+ else
+ {
unsigned char valtmp;
- BITVECP nval = LTG_SIGN(newval);
- int4 i, unionsize=0;
+ BITVECP nval = LTG_SIGN(newval);
+ int4 i,
+ unionsize = 0;
ALOOPBYTE(
- valtmp = nval[i] | orig[i];
- unionsize += SUMBIT(valtmp) - SUMBIT(orig[i]);
+ valtmp = nval[i] | orig[i];
+ unionsize += SUMBIT(valtmp) - SUMBIT(orig[i]);
);
- *penalty = (float)unionsize;
+ *penalty = (float) unionsize;
}
- PG_RETURN_POINTER( penalty );
+ PG_RETURN_POINTER(penalty);
}
-typedef struct {
- OffsetNumber pos;
- int4 cost;
+typedef struct
+{
+ OffsetNumber pos;
+ int4 cost;
} SPLITCOST;
static int
-comparecost( const void *a, const void *b ) {
- return ((SPLITCOST*)a)->cost - ((SPLITCOST*)b)->cost;
+comparecost(const void *a, const void *b)
+{
+ return ((SPLITCOST *) a)->cost - ((SPLITCOST *) b)->cost;
}
-Datum
-_ltree_picksplit(PG_FUNCTION_ARGS) {
- bytea *entryvec = (bytea*) PG_GETARG_POINTER(0);
- GIST_SPLITVEC *v = (GIST_SPLITVEC*) PG_GETARG_POINTER(1);
- OffsetNumber k,j;
- ltree_gist *datum_l, *datum_r;
- ABITVEC union_l, union_r;
- bool firsttime = true;
- int4 size_alpha,size_beta,sizeu,sizei;
- int4 size_waste, waste = 0.0;
- int4 size_l, size_r;
- int4 nbytes;
- OffsetNumber seed_1=0, seed_2=0;
- OffsetNumber *left, *right;
+Datum
+_ltree_picksplit(PG_FUNCTION_ARGS)
+{
+ bytea *entryvec = (bytea *) PG_GETARG_POINTER(0);
+ GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1);
+ OffsetNumber k,
+ j;
+ ltree_gist *datum_l,
+ *datum_r;
+ ABITVEC union_l,
+ union_r;
+ bool firsttime = true;
+ int4 size_alpha,
+ size_beta,
+ sizeu,
+ sizei;
+ int4 size_waste,
+ waste = 0.0;
+ int4 size_l,
+ size_r;
+ int4 nbytes;
+ OffsetNumber seed_1 = 0,
+ seed_2 = 0;
+ OffsetNumber *left,
+ *right;
OffsetNumber maxoff;
- BITVECP ptra, ptrb, ptrc;
- int i;
- unsigned char valtmp;
- SPLITCOST *costvector;
- ltree_gist *_k, *_j;
+ BITVECP ptra,
+ ptrb,
+ ptrc;
+ int i;
+ unsigned char valtmp;
+ SPLITCOST *costvector;
+ ltree_gist *_k,
+ *_j;
maxoff = ((VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY)) - 2;
nbytes = (maxoff + 2) * sizeof(OffsetNumber);
v->spl_left = (OffsetNumber *) palloc(nbytes);
v->spl_right = (OffsetNumber *) palloc(nbytes);
- for (k = FirstOffsetNumber; k < maxoff; k = OffsetNumberNext(k)) {
- _k = GETENTRY(entryvec,k);
- for (j = OffsetNumberNext(k); j <= maxoff; j = OffsetNumberNext(j)) {
- _j = GETENTRY(entryvec,j);
- if ( LTG_ISALLTRUE(_k) || LTG_ISALLTRUE(_j) ) {
+ for (k = FirstOffsetNumber; k < maxoff; k = OffsetNumberNext(k))
+ {
+ _k = GETENTRY(entryvec, k);
+ for (j = OffsetNumberNext(k); j <= maxoff; j = OffsetNumberNext(j))
+ {
+ _j = GETENTRY(entryvec, j);
+ if (LTG_ISALLTRUE(_k) || LTG_ISALLTRUE(_j))
+ {
sizeu = ASIGLENBIT;
- if ( LTG_ISALLTRUE(_k) && LTG_ISALLTRUE(_j) )
+ if (LTG_ISALLTRUE(_k) && LTG_ISALLTRUE(_j))
sizei = ASIGLENBIT;
else
- sizei = ( LTG_ISALLTRUE(_k) ) ?
- sizebitvec( LTG_SIGN(_j) ) : sizebitvec( LTG_SIGN(_k) );
- } else {
+ sizei = (LTG_ISALLTRUE(_k)) ?
+ sizebitvec(LTG_SIGN(_j)) : sizebitvec(LTG_SIGN(_k));
+ }
+ else
+ {
sizeu = sizei = 0;
ptra = LTG_SIGN(_j);
ptrb = LTG_SIGN(_k);
} while(0)
ALOOPBYTE(
- COUNT(0);
- COUNT(1);
- COUNT(2);
- COUNT(3);
- COUNT(4);
- COUNT(5);
- COUNT(6);
- COUNT(7);
- ptra = (BITVECP) ( ((char*)ptra) + 1 );
- ptrb = (BITVECP) ( ((char*)ptrb) + 1 );
+ COUNT(0);
+ COUNT(1);
+ COUNT(2);
+ COUNT(3);
+ COUNT(4);
+ COUNT(5);
+ COUNT(6);
+ COUNT(7);
+ ptra = (BITVECP) (((char *) ptra) + 1);
+ ptrb = (BITVECP) (((char *) ptrb) + 1);
);
}
size_waste = sizeu - sizei;
- if (size_waste > waste || firsttime) {
+ if (size_waste > waste || firsttime)
+ {
waste = size_waste;
seed_1 = k;
seed_2 = j;
right = v->spl_right;
v->spl_nright = 0;
- if ( seed_1 == 0 || seed_2 == 0 ) {
+ if (seed_1 == 0 || seed_2 == 0)
+ {
seed_1 = 1;
seed_2 = 2;
}
/* form initial .. */
- if ( LTG_ISALLTRUE(GETENTRY(entryvec,seed_1)) ) {
- datum_l = (ltree_gist*)palloc( LTG_HDRSIZE );
- datum_l->len = LTG_HDRSIZE; datum_l->flag = LTG_ALLTRUE;
+ if (LTG_ISALLTRUE(GETENTRY(entryvec, seed_1)))
+ {
+ datum_l = (ltree_gist *) palloc(LTG_HDRSIZE);
+ datum_l->len = LTG_HDRSIZE;
+ datum_l->flag = LTG_ALLTRUE;
size_l = ASIGLENBIT;
- } else {
- datum_l = (ltree_gist*)palloc( LTG_HDRSIZE + ASIGLEN );
- datum_l->len = LTG_HDRSIZE + ASIGLEN; datum_l->flag = 0;
- memcpy((void*)LTG_SIGN(datum_l), (void*)LTG_SIGN(GETENTRY(entryvec,seed_1)), sizeof(ABITVEC));
- size_l = sizebitvec( LTG_SIGN(datum_l) );
}
- if ( LTG_ISALLTRUE(GETENTRY(entryvec,seed_2)) ) {
- datum_r = (ltree_gist*)palloc( LTG_HDRSIZE );
- datum_r->len = LTG_HDRSIZE; datum_r->flag = LTG_ALLTRUE;
+ else
+ {
+ datum_l = (ltree_gist *) palloc(LTG_HDRSIZE + ASIGLEN);
+ datum_l->len = LTG_HDRSIZE + ASIGLEN;
+ datum_l->flag = 0;
+ memcpy((void *) LTG_SIGN(datum_l), (void *) LTG_SIGN(GETENTRY(entryvec, seed_1)), sizeof(ABITVEC));
+ size_l = sizebitvec(LTG_SIGN(datum_l));
+ }
+ if (LTG_ISALLTRUE(GETENTRY(entryvec, seed_2)))
+ {
+ datum_r = (ltree_gist *) palloc(LTG_HDRSIZE);
+ datum_r->len = LTG_HDRSIZE;
+ datum_r->flag = LTG_ALLTRUE;
size_r = ASIGLENBIT;
- } else {
- datum_r = (ltree_gist*)palloc( LTG_HDRSIZE + ASIGLEN );
- datum_r->len = LTG_HDRSIZE + ASIGLEN; datum_r->flag = 0;
- memcpy((void*)LTG_SIGN(datum_r), (void*)LTG_SIGN(GETENTRY(entryvec,seed_2)), sizeof(ABITVEC));
- size_r = sizebitvec( LTG_SIGN(datum_r) );
+ }
+ else
+ {
+ datum_r = (ltree_gist *) palloc(LTG_HDRSIZE + ASIGLEN);
+ datum_r->len = LTG_HDRSIZE + ASIGLEN;
+ datum_r->flag = 0;
+ memcpy((void *) LTG_SIGN(datum_r), (void *) LTG_SIGN(GETENTRY(entryvec, seed_2)), sizeof(ABITVEC));
+ size_r = sizebitvec(LTG_SIGN(datum_r));
}
maxoff = OffsetNumberNext(maxoff);
/* sort before ... */
- costvector=(SPLITCOST*)palloc( sizeof(SPLITCOST)*maxoff );
- for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j)) {
- costvector[j-1].pos = j;
- _j = GETENTRY(entryvec,j);
- if ( LTG_ISALLTRUE(_j) ) {
+ costvector = (SPLITCOST *) palloc(sizeof(SPLITCOST) * maxoff);
+ for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j))
+ {
+ costvector[j - 1].pos = j;
+ _j = GETENTRY(entryvec, j);
+ if (LTG_ISALLTRUE(_j))
+ {
size_alpha = ASIGLENBIT - size_l;
- size_beta = ASIGLENBIT - size_r;
- } else {
- ptra = LTG_SIGN( datum_l );
- ptrb = LTG_SIGN( datum_r );
- ptrc = LTG_SIGN( _j );
+ size_beta = ASIGLENBIT - size_r;
+ }
+ else
+ {
+ ptra = LTG_SIGN(datum_l);
+ ptrb = LTG_SIGN(datum_r);
+ ptrc = LTG_SIGN(_j);
size_beta = size_alpha = 0;
- if ( LTG_ISALLTRUE(datum_l) ) {
- if ( !LTG_ISALLTRUE(datum_r) ) {
+ if (LTG_ISALLTRUE(datum_l))
+ {
+ if (!LTG_ISALLTRUE(datum_r))
+ {
ALOOPBIT(
- if ( GETBIT(ptrc,i) && ! GETBIT(ptrb,i) )
- size_beta++;
+ if (GETBIT(ptrc, i) && !GETBIT(ptrb, i))
+ size_beta++;
);
}
- } else if ( LTG_ISALLTRUE(datum_r) ) {
- if ( !LTG_ISALLTRUE(datum_l) ) {
+ }
+ else if (LTG_ISALLTRUE(datum_r))
+ {
+ if (!LTG_ISALLTRUE(datum_l))
+ {
ALOOPBIT(
- if ( GETBIT(ptrc,i) && ! GETBIT(ptra,i) )
- size_alpha++;
+ if (GETBIT(ptrc, i) && !GETBIT(ptra, i))
+ size_alpha++;
);
}
- } else {
+ }
+ else
+ {
ALOOPBIT(
- if ( GETBIT(ptrc,i) && ! GETBIT(ptra,i) )
- size_alpha++;
- if ( GETBIT(ptrc,i) && ! GETBIT(ptrb,i) )
- size_beta++;
+ if (GETBIT(ptrc, i) && !GETBIT(ptra, i))
+ size_alpha++;
+ if (GETBIT(ptrc, i) && !GETBIT(ptrb, i))
+ size_beta++;
);
}
}
- costvector[j-1].cost = abs( size_alpha - size_beta );
+ costvector[j - 1].cost = abs(size_alpha - size_beta);
}
- qsort( (void*)costvector, maxoff, sizeof(SPLITCOST), comparecost );
+ qsort((void *) costvector, maxoff, sizeof(SPLITCOST), comparecost);
- for (k = 0; k < maxoff; k++) {
+ for (k = 0; k < maxoff; k++)
+ {
j = costvector[k].pos;
- _j = GETENTRY(entryvec,j);
- if ( j == seed_1 ) {
+ _j = GETENTRY(entryvec, j);
+ if (j == seed_1)
+ {
*left++ = j;
v->spl_nleft++;
continue;
- } else if ( j == seed_2 ) {
+ }
+ else if (j == seed_2)
+ {
*right++ = j;
v->spl_nright++;
continue;
}
- if ( LTG_ISALLTRUE(datum_l) || LTG_ISALLTRUE(_j) ) {
+ if (LTG_ISALLTRUE(datum_l) || LTG_ISALLTRUE(_j))
size_alpha = ASIGLENBIT;
- } else {
+ else
+ {
ptra = LTG_SIGN(_j);
ptrb = LTG_SIGN(datum_l);
size_alpha = 0;
ALOOPBYTE(
- valtmp = union_l[i] = ptra[i] | ptrb[i];
- size_alpha += SUMBIT( valtmp );
+ valtmp = union_l[i] = ptra[i] | ptrb[i];
+ size_alpha += SUMBIT(valtmp);
);
}
- if ( LTG_ISALLTRUE(datum_r) || LTG_ISALLTRUE(_j) ) {
+ if (LTG_ISALLTRUE(datum_r) || LTG_ISALLTRUE(_j))
size_beta = ASIGLENBIT;
- } else {
+ else
+ {
ptra = LTG_SIGN(_j);
ptrb = LTG_SIGN(datum_r);
size_beta = 0;
ALOOPBYTE(
- valtmp = union_r[i] = ptra[i] | ptrb[i];
- size_beta += SUMBIT( valtmp );
+ valtmp = union_r[i] = ptra[i] | ptrb[i];
+ size_beta += SUMBIT(valtmp);
);
}
- if (size_alpha - size_l < size_beta - size_r + WISH_F(v->spl_nleft, v->spl_nright, 0.1)) {
- if ( ! LTG_ISALLTRUE( datum_l ) ) {
- if ( size_alpha == ASIGLENBIT ) {
- if ( size_alpha != size_l )
- MemSet( (void*)LTG_SIGN(datum_l),0xff, sizeof(ABITVEC));
- } else
- memcpy( (void*)LTG_SIGN(datum_l), (void*)union_l, sizeof(ABITVEC) );
+ if (size_alpha - size_l < size_beta - size_r + WISH_F(v->spl_nleft, v->spl_nright, 0.1))
+ {
+ if (!LTG_ISALLTRUE(datum_l))
+ {
+ if (size_alpha == ASIGLENBIT)
+ {
+ if (size_alpha != size_l)
+ MemSet((void *) LTG_SIGN(datum_l), 0xff, sizeof(ABITVEC));
+ }
+ else
+ memcpy((void *) LTG_SIGN(datum_l), (void *) union_l, sizeof(ABITVEC));
}
size_l = size_alpha;
*left++ = j;
v->spl_nleft++;
- } else {
- if ( ! LTG_ISALLTRUE( datum_r ) ) {
- if ( size_beta == ASIGLENBIT ) {
- if ( size_beta != size_r )
- MemSet( (void*)LTG_SIGN(datum_r),0xff, sizeof(ABITVEC));
- } else
- memcpy( (void*)LTG_SIGN(datum_r), (void*)union_r, sizeof(ABITVEC) );
+ }
+ else
+ {
+ if (!LTG_ISALLTRUE(datum_r))
+ {
+ if (size_beta == ASIGLENBIT)
+ {
+ if (size_beta != size_r)
+ MemSet((void *) LTG_SIGN(datum_r), 0xff, sizeof(ABITVEC));
+ }
+ else
+ memcpy((void *) LTG_SIGN(datum_r), (void *) union_r, sizeof(ABITVEC));
}
size_r = size_beta;
*right++ = j;
v->spl_ldatum = PointerGetDatum(datum_l);
v->spl_rdatum = PointerGetDatum(datum_r);
- PG_RETURN_POINTER( v );
+ PG_RETURN_POINTER(v);
}
static bool
-gist_te(ltree_gist *key, ltree* query) {
- ltree_level *curq = LTREE_FIRST(query);
- BITVECP sign = LTG_SIGN(key);
- int qlen = query->numlevel;
+gist_te(ltree_gist * key, ltree * query)
+{
+ ltree_level *curq = LTREE_FIRST(query);
+ BITVECP sign = LTG_SIGN(key);
+ int qlen = query->numlevel;
unsigned int hv;
- if ( LTG_ISALLTRUE(key) )
+ if (LTG_ISALLTRUE(key))
return true;
- while( qlen>0 ) {
- hv = ltree_crc32_sz(curq->name,curq->len);
- if ( ! GETBIT( sign, AHASHVAL(hv) ) )
- return false;
+ while (qlen > 0)
+ {
+ hv = ltree_crc32_sz(curq->name, curq->len);
+ if (!GETBIT(sign, AHASHVAL(hv)))
+ return false;
curq = LEVEL_NEXT(curq);
qlen--;
}
}
static bool
-checkcondition_bit(void *checkval, ITEM* val ) {
- return ( FLG_CANLOOKSIGN(val->flag) ) ? GETBIT( checkval, AHASHVAL( val->val ) ) : true;
+checkcondition_bit(void *checkval, ITEM * val)
+{
+ return (FLG_CANLOOKSIGN(val->flag)) ? GETBIT(checkval, AHASHVAL(val->val)) : true;
}
static bool
-gist_qtxt(ltree_gist *key, ltxtquery* query) {
- if ( LTG_ISALLTRUE(key) )
+gist_qtxt(ltree_gist * key, ltxtquery * query)
+{
+ if (LTG_ISALLTRUE(key))
return true;
-
+
return ltree_execute(
- GETQUERY(query),
- (void*)LTG_SIGN(key), false,
- checkcondition_bit
- );
+ GETQUERY(query),
+ (void *) LTG_SIGN(key), false,
+ checkcondition_bit
+ );
}
static bool
-gist_qe(ltree_gist *key, lquery* query) {
- lquery_level *curq = LQUERY_FIRST(query);
- BITVECP sign = LTG_SIGN(key);
- int qlen = query->numlevel;
-
- if ( LTG_ISALLTRUE(key) )
+gist_qe(ltree_gist * key, lquery * query)
+{
+ lquery_level *curq = LQUERY_FIRST(query);
+ BITVECP sign = LTG_SIGN(key);
+ int qlen = query->numlevel;
+
+ if (LTG_ISALLTRUE(key))
return true;
-
- while( qlen>0 ) {
- if ( curq->numvar && LQL_CANLOOKSIGN(curq) ) {
- bool isexist=false;
- int vlen = curq->numvar;
+
+ while (qlen > 0)
+ {
+ if (curq->numvar && LQL_CANLOOKSIGN(curq))
+ {
+ bool isexist = false;
+ int vlen = curq->numvar;
lquery_variant *curv = LQL_FIRST(curq);
- while( vlen>0 ) {
- if ( GETBIT( sign, AHASHVAL( curv->val ) ) ) {
- isexist=true;
+
+ while (vlen > 0)
+ {
+ if (GETBIT(sign, AHASHVAL(curv->val)))
+ {
+ isexist = true;
break;
}
curv = LVAR_NEXT(curv);
vlen--;
}
- if ( !isexist )
+ if (!isexist)
return false;
}
-
+
curq = LQL_NEXT(curq);
qlen--;
}
}
-Datum
-_ltree_consistent(PG_FUNCTION_ARGS) {
- GISTENTRY *entry = (GISTENTRY*)PG_GETARG_POINTER(0);
- char *query = (char*)DatumGetPointer( PG_DETOAST_DATUM(PG_GETARG_DATUM(1)) );
- ltree_gist *key = (ltree_gist*)DatumGetPointer( entry->key );
+Datum
+_ltree_consistent(PG_FUNCTION_ARGS)
+{
+ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
+ char *query = (char *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(1)));
+ ltree_gist *key = (ltree_gist *) DatumGetPointer(entry->key);
StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
- bool res = false;
+ bool res = false;
-#ifndef assert_enabled
+#ifndef assert_enabled
#define assert_enabled 0
#endif
-
- switch( strategy ) {
+
+ switch (strategy)
+ {
case 10:
case 11:
- res = gist_te(key, (ltree*)query);
+ res = gist_te(key, (ltree *) query);
break;
case 12:
case 13:
- res = gist_qe(key, (lquery*)query);
- break;
+ res = gist_qe(key, (lquery *) query);
+ break;
case 14:
case 15:
- res = gist_qtxt(key, (ltxtquery*)query);
- break;
+ res = gist_qtxt(key, (ltxtquery *) query);
+ break;
default:
- elog(ERROR,"Unknown StrategyNumber: %d", strategy);
+ elog(ERROR, "Unknown StrategyNumber: %d", strategy);
}
PG_RETURN_BOOL(res);
}
-
/*
- * op function for ltree[]
+ * op function for ltree[]
* Teodor Sigaev <teodor@stack.net>
*/
PG_FUNCTION_INFO_V1(_ltxtq_exec);
PG_FUNCTION_INFO_V1(_ltxtq_rexec);
-Datum _ltree_r_isparent(PG_FUNCTION_ARGS);
-Datum _ltree_r_risparent(PG_FUNCTION_ARGS);
+Datum _ltree_r_isparent(PG_FUNCTION_ARGS);
+Datum _ltree_r_risparent(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(_ltree_extract_isparent);
PG_FUNCTION_INFO_V1(_ltree_extract_risparent);
PG_FUNCTION_INFO_V1(_ltq_extract_regex);
PG_FUNCTION_INFO_V1(_ltxtq_extract_exec);
-Datum _ltree_extract_isparent(PG_FUNCTION_ARGS);
-Datum _ltree_extract_risparent(PG_FUNCTION_ARGS);
-Datum _ltq_extract_regex(PG_FUNCTION_ARGS);
-Datum _ltxtq_extract_exec(PG_FUNCTION_ARGS);
+Datum _ltree_extract_isparent(PG_FUNCTION_ARGS);
+Datum _ltree_extract_risparent(PG_FUNCTION_ARGS);
+Datum _ltq_extract_regex(PG_FUNCTION_ARGS);
+Datum _ltxtq_extract_exec(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(_lca);
-Datum _lca(PG_FUNCTION_ARGS);
+Datum _lca(PG_FUNCTION_ARGS);
+
+typedef Datum (*PGCALL2) (PG_FUNCTION_ARGS);
-typedef Datum (*PGCALL2)(PG_FUNCTION_ARGS);
#define NEXTVAL(x) ( (ltree*)( (char*)(x) + INTALIGN( VARSIZE(x) ) ) )
static bool
-array_iterator( ArrayType *la, PGCALL2 callback, void* param, ltree ** found) {
- int num=ArrayGetNItems( ARR_NDIM(la), ARR_DIMS(la));
- ltree *item = (ltree*)ARR_DATA_PTR(la);
-
- if ( ARR_NDIM(la) !=1 )
- elog(ERROR,"Dimension of array != 1");
-
- if ( found )
- *found=NULL;
- while( num>0 ) {
- if ( DatumGetBool( DirectFunctionCall2( callback,
- PointerGetDatum(item), PointerGetDatum(param) ) ) ) {
-
- if ( found )
+array_iterator(ArrayType *la, PGCALL2 callback, void *param, ltree ** found)
+{
+ int num = ArrayGetNItems(ARR_NDIM(la), ARR_DIMS(la));
+ ltree *item = (ltree *) ARR_DATA_PTR(la);
+
+ if (ARR_NDIM(la) != 1)
+ elog(ERROR, "Dimension of array != 1");
+
+ if (found)
+ *found = NULL;
+ while (num > 0)
+ {
+ if (DatumGetBool(DirectFunctionCall2(callback,
+ PointerGetDatum(item), PointerGetDatum(param))))
+ {
+
+ if (found)
*found = item;
return true;
}
num--;
- item = NEXTVAL(item);
+ item = NEXTVAL(item);
}
return false;
}
Datum
-_ltree_isparent(PG_FUNCTION_ARGS) {
- ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
- ltree *query = PG_GETARG_LTREE(1);
- bool res = array_iterator( la, ltree_isparent, (void*)query, NULL );
- PG_FREE_IF_COPY(la,0);
- PG_FREE_IF_COPY(query,1);
+_ltree_isparent(PG_FUNCTION_ARGS)
+{
+ ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
+ ltree *query = PG_GETARG_LTREE(1);
+ bool res = array_iterator(la, ltree_isparent, (void *) query, NULL);
+
+ PG_FREE_IF_COPY(la, 0);
+ PG_FREE_IF_COPY(query, 1);
PG_RETURN_BOOL(res);
}
Datum
-_ltree_r_isparent(PG_FUNCTION_ARGS) {
- PG_RETURN_DATUM( DirectFunctionCall2( _ltree_isparent,
- PG_GETARG_DATUM(1),
- PG_GETARG_DATUM(0)
- ) );
+_ltree_r_isparent(PG_FUNCTION_ARGS)
+{
+ PG_RETURN_DATUM(DirectFunctionCall2(_ltree_isparent,
+ PG_GETARG_DATUM(1),
+ PG_GETARG_DATUM(0)
+ ));
}
Datum
-_ltree_risparent(PG_FUNCTION_ARGS) {
- ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
- ltree *query = PG_GETARG_LTREE(1);
- bool res = array_iterator( la, ltree_risparent, (void*)query, NULL );
- PG_FREE_IF_COPY(la,0);
- PG_FREE_IF_COPY(query,1);
+_ltree_risparent(PG_FUNCTION_ARGS)
+{
+ ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
+ ltree *query = PG_GETARG_LTREE(1);
+ bool res = array_iterator(la, ltree_risparent, (void *) query, NULL);
+
+ PG_FREE_IF_COPY(la, 0);
+ PG_FREE_IF_COPY(query, 1);
PG_RETURN_BOOL(res);
}
Datum
-_ltree_r_risparent(PG_FUNCTION_ARGS) {
- PG_RETURN_DATUM( DirectFunctionCall2( _ltree_risparent,
- PG_GETARG_DATUM(1),
- PG_GETARG_DATUM(0)
- ) );
+_ltree_r_risparent(PG_FUNCTION_ARGS)
+{
+ PG_RETURN_DATUM(DirectFunctionCall2(_ltree_risparent,
+ PG_GETARG_DATUM(1),
+ PG_GETARG_DATUM(0)
+ ));
}
Datum
-_ltq_regex(PG_FUNCTION_ARGS) {
- ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
- lquery *query = PG_GETARG_LQUERY(1);
- bool res = array_iterator( la, ltq_regex, (void*)query, NULL );
- PG_FREE_IF_COPY(la,0);
- PG_FREE_IF_COPY(query,1);
+_ltq_regex(PG_FUNCTION_ARGS)
+{
+ ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
+ lquery *query = PG_GETARG_LQUERY(1);
+ bool res = array_iterator(la, ltq_regex, (void *) query, NULL);
+
+ PG_FREE_IF_COPY(la, 0);
+ PG_FREE_IF_COPY(query, 1);
PG_RETURN_BOOL(res);
}
Datum
-_ltq_rregex(PG_FUNCTION_ARGS) {
- PG_RETURN_DATUM( DirectFunctionCall2( _ltq_regex,
- PG_GETARG_DATUM(1),
- PG_GETARG_DATUM(0)
- ) );
+_ltq_rregex(PG_FUNCTION_ARGS)
+{
+ PG_RETURN_DATUM(DirectFunctionCall2(_ltq_regex,
+ PG_GETARG_DATUM(1),
+ PG_GETARG_DATUM(0)
+ ));
}
-Datum
-_ltxtq_exec(PG_FUNCTION_ARGS) {
- ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
- ltxtquery *query = PG_GETARG_LTXTQUERY(1);
- bool res = array_iterator( la, ltxtq_exec, (void*)query, NULL );
- PG_FREE_IF_COPY(la,0);
- PG_FREE_IF_COPY(query,1);
+Datum
+_ltxtq_exec(PG_FUNCTION_ARGS)
+{
+ ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
+ ltxtquery *query = PG_GETARG_LTXTQUERY(1);
+ bool res = array_iterator(la, ltxtq_exec, (void *) query, NULL);
+
+ PG_FREE_IF_COPY(la, 0);
+ PG_FREE_IF_COPY(query, 1);
PG_RETURN_BOOL(res);
}
Datum
-_ltxtq_rexec(PG_FUNCTION_ARGS) {
- PG_RETURN_DATUM( DirectFunctionCall2( _ltxtq_exec,
- PG_GETARG_DATUM(1),
- PG_GETARG_DATUM(0)
- ) );
+_ltxtq_rexec(PG_FUNCTION_ARGS)
+{
+ PG_RETURN_DATUM(DirectFunctionCall2(_ltxtq_exec,
+ PG_GETARG_DATUM(1),
+ PG_GETARG_DATUM(0)
+ ));
}
-Datum
-_ltree_extract_isparent(PG_FUNCTION_ARGS) {
- ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
- ltree *query = PG_GETARG_LTREE(1);
- ltree *found,*item;
-
- if ( !array_iterator( la, ltree_isparent, (void*)query, &found ) ) {
- PG_FREE_IF_COPY(la,0);
- PG_FREE_IF_COPY(query,1);
+Datum
+_ltree_extract_isparent(PG_FUNCTION_ARGS)
+{
+ ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
+ ltree *query = PG_GETARG_LTREE(1);
+ ltree *found,
+ *item;
+
+ if (!array_iterator(la, ltree_isparent, (void *) query, &found))
+ {
+ PG_FREE_IF_COPY(la, 0);
+ PG_FREE_IF_COPY(query, 1);
PG_RETURN_NULL();
}
- item = (ltree*)palloc( found->len );
- memcpy( item, found, found->len );
-
- PG_FREE_IF_COPY(la,0);
- PG_FREE_IF_COPY(query,1);
+ item = (ltree *) palloc(found->len);
+ memcpy(item, found, found->len);
+
+ PG_FREE_IF_COPY(la, 0);
+ PG_FREE_IF_COPY(query, 1);
PG_RETURN_POINTER(item);
}
-Datum
-_ltree_extract_risparent(PG_FUNCTION_ARGS) {
- ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
- ltree *query = PG_GETARG_LTREE(1);
- ltree *found,*item;
-
- if ( !array_iterator( la, ltree_risparent, (void*)query, &found ) ) {
- PG_FREE_IF_COPY(la,0);
- PG_FREE_IF_COPY(query,1);
+Datum
+_ltree_extract_risparent(PG_FUNCTION_ARGS)
+{
+ ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
+ ltree *query = PG_GETARG_LTREE(1);
+ ltree *found,
+ *item;
+
+ if (!array_iterator(la, ltree_risparent, (void *) query, &found))
+ {
+ PG_FREE_IF_COPY(la, 0);
+ PG_FREE_IF_COPY(query, 1);
PG_RETURN_NULL();
}
- item = (ltree*)palloc( found->len );
- memcpy( item, found, found->len );
-
- PG_FREE_IF_COPY(la,0);
- PG_FREE_IF_COPY(query,1);
+ item = (ltree *) palloc(found->len);
+ memcpy(item, found, found->len);
+
+ PG_FREE_IF_COPY(la, 0);
+ PG_FREE_IF_COPY(query, 1);
PG_RETURN_POINTER(item);
}
-Datum
-_ltq_extract_regex(PG_FUNCTION_ARGS) {
- ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
- lquery *query = PG_GETARG_LQUERY(1);
- ltree *found,*item;
-
- if ( !array_iterator( la, ltq_regex, (void*)query, &found ) ) {
- PG_FREE_IF_COPY(la,0);
- PG_FREE_IF_COPY(query,1);
+Datum
+_ltq_extract_regex(PG_FUNCTION_ARGS)
+{
+ ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
+ lquery *query = PG_GETARG_LQUERY(1);
+ ltree *found,
+ *item;
+
+ if (!array_iterator(la, ltq_regex, (void *) query, &found))
+ {
+ PG_FREE_IF_COPY(la, 0);
+ PG_FREE_IF_COPY(query, 1);
PG_RETURN_NULL();
}
- item = (ltree*)palloc( found->len );
- memcpy( item, found, found->len );
-
- PG_FREE_IF_COPY(la,0);
- PG_FREE_IF_COPY(query,1);
+ item = (ltree *) palloc(found->len);
+ memcpy(item, found, found->len);
+
+ PG_FREE_IF_COPY(la, 0);
+ PG_FREE_IF_COPY(query, 1);
PG_RETURN_POINTER(item);
}
-Datum
-_ltxtq_extract_exec(PG_FUNCTION_ARGS) {
- ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
- ltxtquery *query = PG_GETARG_LTXTQUERY(1);
- ltree *found,*item;
-
- if ( !array_iterator( la, ltxtq_exec, (void*)query, &found ) ) {
- PG_FREE_IF_COPY(la,0);
- PG_FREE_IF_COPY(query,1);
+Datum
+_ltxtq_extract_exec(PG_FUNCTION_ARGS)
+{
+ ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
+ ltxtquery *query = PG_GETARG_LTXTQUERY(1);
+ ltree *found,
+ *item;
+
+ if (!array_iterator(la, ltxtq_exec, (void *) query, &found))
+ {
+ PG_FREE_IF_COPY(la, 0);
+ PG_FREE_IF_COPY(query, 1);
PG_RETURN_NULL();
}
- item = (ltree*)palloc( found->len );
- memcpy( item, found, found->len );
-
- PG_FREE_IF_COPY(la,0);
- PG_FREE_IF_COPY(query,1);
+ item = (ltree *) palloc(found->len);
+ memcpy(item, found, found->len);
+
+ PG_FREE_IF_COPY(la, 0);
+ PG_FREE_IF_COPY(query, 1);
PG_RETURN_POINTER(item);
}
Datum
-_lca(PG_FUNCTION_ARGS) {
- ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
- int num=ArrayGetNItems( ARR_NDIM(la), ARR_DIMS(la));
- ltree *item = (ltree*)ARR_DATA_PTR(la);
- ltree **a,*res;
-
- a=(ltree**)palloc( sizeof(ltree*) * num );
- while( num>0 ) {
+_lca(PG_FUNCTION_ARGS)
+{
+ ArrayType *la = PG_GETARG_ARRAYTYPE_P(0);
+ int num = ArrayGetNItems(ARR_NDIM(la), ARR_DIMS(la));
+ ltree *item = (ltree *) ARR_DATA_PTR(la);
+ ltree **a,
+ *res;
+
+ a = (ltree **) palloc(sizeof(ltree *) * num);
+ while (num > 0)
+ {
num--;
a[num] = item;
item = NEXTVAL(item);
}
- res = lca_inner(a, ArrayGetNItems( ARR_NDIM(la), ARR_DIMS(la)));
+ res = lca_inner(a, ArrayGetNItems(ARR_NDIM(la), ARR_DIMS(la)));
pfree(a);
- PG_FREE_IF_COPY(la,0);
+ PG_FREE_IF_COPY(la, 0);
- if ( res )
- PG_RETURN_POINTER(res);
- else
- PG_RETURN_NULL();
+ if (res)
+ PG_RETURN_POINTER(res);
+ else
+ PG_RETURN_NULL();
}
-
len = 0;
nr = size;
for (len += nr, p = buf; nr--; ++p)
- _CRC32_(crc, TOLOWER((unsigned int)*p));
+ _CRC32_(crc, TOLOWER((unsigned int) *p));
return ~crc;
}
/*
- * op function for ltree and lquery
+ * op function for ltree and lquery
* Teodor Sigaev <teodor@stack.net>
*/
PG_FUNCTION_INFO_V1(ltq_regex);
PG_FUNCTION_INFO_V1(ltq_rregex);
-typedef struct {
- lquery_level *q;
- int nq;
- ltree_level *t;
- int nt;
- int posq;
- int post;
-} FieldNot;
+typedef struct
+{
+ lquery_level *q;
+ int nq;
+ ltree_level *t;
+ int nt;
+ int posq;
+ int post;
+} FieldNot;
static char *
-getlexem(char *start, char *end, int *len) {
- char *ptr;
-
- while( start<end && *start == '_' )
+getlexem(char *start, char *end, int *len)
+{
+ char *ptr;
+
+ while (start < end && *start == '_')
start++;
ptr = start;
- if ( ptr == end )
+ if (ptr == end)
return NULL;
- while( ptr < end && *ptr != '_')
+ while (ptr < end && *ptr != '_')
ptr++;
*len = ptr - start;
}
bool
-compare_subnode( ltree_level *t, char *qn, int len, int (*cmpptr)(const char *,const char *,size_t), bool anyend ) {
- char *endt = t->name + t->len;
- char *endq = qn + len;
- char *tn;
- int lent,lenq;
- bool isok;
-
- while( (qn=getlexem(qn,endq,&lenq)) != NULL ) {
- tn=t->name;
+ compare_subnode(ltree_level * t, char *qn, int len, int (*cmpptr) (const char *, const char *, size_t), bool anyend)
+{
+ char *endt = t->name + t->len;
+ char *endq = qn + len;
+ char *tn;
+ int lent,
+ lenq;
+ bool isok;
+
+ while ((qn = getlexem(qn, endq, &lenq)) != NULL)
+ {
+ tn = t->name;
isok = false;
- while( (tn=getlexem(tn,endt,&lent)) != NULL ) {
- if (
+ while ((tn = getlexem(tn, endt, &lent)) != NULL)
+ {
+ if (
(
- lent == lenq ||
- ( lent > lenq && anyend )
- ) &&
- (*cmpptr)(qn,tn,lenq) == 0 ) {
-
- isok = true;
+ lent == lenq ||
+ (lent > lenq && anyend)
+ ) &&
+ (*cmpptr) (qn, tn, lenq) == 0)
+ {
+
+ isok = true;
break;
}
tn += lent;
}
- if ( !isok )
+ if (!isok)
return false;
qn += lenq;
}
}
static bool
-checkLevel( lquery_level *curq, ltree_level *curt ) {
- int (*cmpptr)(const char *,const char *,size_t);
+checkLevel(lquery_level * curq, ltree_level * curt)
+{
+ int (*cmpptr) (const char *, const char *, size_t);
lquery_variant *curvar = LQL_FIRST(curq);
- int i;
-
- for(i=0;i<curq->numvar;i++) {
- cmpptr = ( curvar->flag & LVAR_INCASE ) ? strncasecmp : strncmp;
+ int i;
- if ( curvar->flag & LVAR_SUBLEXEM ) {
- if ( compare_subnode(curt, curvar->name, curvar->len, cmpptr, (curvar->flag & LVAR_ANYEND) ) )
+ for (i = 0; i < curq->numvar; i++)
+ {
+ cmpptr = (curvar->flag & LVAR_INCASE) ? strncasecmp : strncmp;
+
+ if (curvar->flag & LVAR_SUBLEXEM)
+ {
+ if (compare_subnode(curt, curvar->name, curvar->len, cmpptr, (curvar->flag & LVAR_ANYEND)))
return true;
- } else if (
- (
- curvar->len == curt->len ||
- ( curt->len > curvar->len && (curvar->flag & LVAR_ANYEND) )
- ) &&
- (*cmpptr)( curvar->name, curt->name, curvar->len) == 0 ) {
+ }
+ else if (
+ (
+ curvar->len == curt->len ||
+ (curt->len > curvar->len && (curvar->flag & LVAR_ANYEND))
+ ) &&
+ (*cmpptr) (curvar->name, curt->name, curvar->len) == 0)
+ {
return true;
}
- curvar = LVAR_NEXT(curvar);
+ curvar = LVAR_NEXT(curvar);
}
return false;
}
elog(NOTICE,"posQ:%d lenQ:%d posT:%d lenT:%d", fn->posq,fn->nq,fn->post,fn->nt);
fn++;
}
-}
+}
*/
static bool
-checkCond( lquery_level *curq, int query_numlevel, ltree_level *curt, int tree_numlevel, FieldNot *ptr ) {
- uint32 low_pos=0,high_pos=0,cur_tpos=0;
- int tlen = tree_numlevel, qlen = query_numlevel;
- int isok;
- lquery_level *prevq=NULL;
- ltree_level *prevt=NULL;
-
- while( tlen >0 && qlen>0 ) {
- if ( curq->numvar ) {
+checkCond(lquery_level * curq, int query_numlevel, ltree_level * curt, int tree_numlevel, FieldNot * ptr)
+{
+ uint32 low_pos = 0,
+ high_pos = 0,
+ cur_tpos = 0;
+ int tlen = tree_numlevel,
+ qlen = query_numlevel;
+ int isok;
+ lquery_level *prevq = NULL;
+ ltree_level *prevt = NULL;
+
+ while (tlen > 0 && qlen > 0)
+ {
+ if (curq->numvar)
+ {
prevt = curt;
- while ( cur_tpos < low_pos ) {
+ while (cur_tpos < low_pos)
+ {
curt = LEVEL_NEXT(curt);
tlen--;
cur_tpos++;
- if ( tlen==0 )
+ if (tlen == 0)
return false;
- if ( ptr && ptr->q )
+ if (ptr && ptr->q)
ptr->nt++;
}
-
- if ( ptr && curq->flag & LQL_NOT ) {
- if ( !(prevq && prevq->numvar == 0) )
+
+ if (ptr && curq->flag & LQL_NOT)
+ {
+ if (!(prevq && prevq->numvar == 0))
prevq = curq;
- if ( ptr->q == NULL ) {
+ if (ptr->q == NULL)
+ {
ptr->t = prevt;
ptr->q = prevq;
- ptr->nt=1;
- ptr->nq=1 + ( (prevq==curq) ? 0 : 1 );
- ptr->posq = query_numlevel - qlen - ( (prevq==curq) ? 0 : 1 );
+ ptr->nt = 1;
+ ptr->nq = 1 + ((prevq == curq) ? 0 : 1);
+ ptr->posq = query_numlevel - qlen - ((prevq == curq) ? 0 : 1);
ptr->post = cur_tpos;
- } else {
+ }
+ else
+ {
ptr->nt++;
ptr->nq++;
}
- if ( qlen == 1 && ptr->q->numvar==0 )
- ptr->nt = tree_numlevel - ptr->post;
+ if (qlen == 1 && ptr->q->numvar == 0)
+ ptr->nt = tree_numlevel - ptr->post;
curt = LEVEL_NEXT(curt);
tlen--;
cur_tpos++;
- if ( high_pos < cur_tpos )
+ if (high_pos < cur_tpos)
high_pos++;
- } else {
+ }
+ else
+ {
isok = false;
- while( cur_tpos <= high_pos && tlen > 0 && !isok) {
+ while (cur_tpos <= high_pos && tlen > 0 && !isok)
+ {
isok = checkLevel(curq, curt);
curt = LEVEL_NEXT(curt);
tlen--;
cur_tpos++;
- if ( !isok && ptr )
+ if (!isok && ptr)
ptr->nt++;
}
- if ( !isok )
+ if (!isok)
return false;
- if (ptr && ptr->q) {
- if ( checkCond(ptr->q,ptr->nq,ptr->t,ptr->nt,NULL) )
+ if (ptr && ptr->q)
+ {
+ if (checkCond(ptr->q, ptr->nq, ptr->t, ptr->nt, NULL))
return false;
ptr->q = NULL;
}
- low_pos=cur_tpos; high_pos=cur_tpos;
+ low_pos = cur_tpos;
+ high_pos = cur_tpos;
}
- } else {
+ }
+ else
+ {
low_pos = cur_tpos + curq->low;
high_pos = cur_tpos + curq->high;
- if ( ptr && ptr->q ) {
+ if (ptr && ptr->q)
+ {
ptr->nq++;
- if ( qlen==1 )
+ if (qlen == 1)
ptr->nt = tree_numlevel - ptr->post;
}
}
prevq = curq;
curq = LQL_NEXT(curq);
qlen--;
- }
+ }
- if ( low_pos > tree_numlevel || tree_numlevel > high_pos )
+ if (low_pos > tree_numlevel || tree_numlevel > high_pos)
return false;
- while( qlen>0 ) {
- if ( curq->numvar ) {
- if ( ! (curq->flag & LQL_NOT) )
+ while (qlen > 0)
+ {
+ if (curq->numvar)
+ {
+ if (!(curq->flag & LQL_NOT))
return false;
- } else {
+ }
+ else
+ {
low_pos = cur_tpos + curq->low;
high_pos = cur_tpos + curq->high;
}
qlen--;
}
- if ( low_pos > tree_numlevel || tree_numlevel > high_pos )
+ if (low_pos > tree_numlevel || tree_numlevel > high_pos)
return false;
-
- if ( ptr && ptr->q && checkCond(ptr->q,ptr->nq,ptr->t,ptr->nt,NULL) )
+
+ if (ptr && ptr->q && checkCond(ptr->q, ptr->nq, ptr->t, ptr->nt, NULL))
return false;
-
+
return true;
}
Datum
-ltq_regex(PG_FUNCTION_ARGS) {
- ltree *tree = PG_GETARG_LTREE(0);
- lquery *query = PG_GETARG_LQUERY(1);
- bool res= false;
+ltq_regex(PG_FUNCTION_ARGS)
+{
+ ltree *tree = PG_GETARG_LTREE(0);
+ lquery *query = PG_GETARG_LQUERY(1);
+ bool res = false;
- if ( query->flag & LQUERY_HASNOT ) {
+ if (query->flag & LQUERY_HASNOT)
+ {
FieldNot fn;
- fn.q=NULL;
+ fn.q = NULL;
- res = checkCond( LQUERY_FIRST(query), query->numlevel,
- LTREE_FIRST(tree), tree->numlevel, &fn );
- } else {
- res = checkCond( LQUERY_FIRST(query), query->numlevel,
- LTREE_FIRST(tree), tree->numlevel, NULL );
+ res = checkCond(LQUERY_FIRST(query), query->numlevel,
+ LTREE_FIRST(tree), tree->numlevel, &fn);
+ }
+ else
+ {
+ res = checkCond(LQUERY_FIRST(query), query->numlevel,
+ LTREE_FIRST(tree), tree->numlevel, NULL);
}
- PG_FREE_IF_COPY(tree,0);
- PG_FREE_IF_COPY(query,1);
- PG_RETURN_BOOL(res);
+ PG_FREE_IF_COPY(tree, 0);
+ PG_FREE_IF_COPY(query, 1);
+ PG_RETURN_BOOL(res);
}
-Datum
-ltq_rregex(PG_FUNCTION_ARGS) {
- PG_RETURN_DATUM( DirectFunctionCall2( ltq_regex,
- PG_GETARG_DATUM(1),
- PG_GETARG_DATUM(0)
- ) );
+Datum
+ltq_rregex(PG_FUNCTION_ARGS)
+{
+ PG_RETURN_DATUM(DirectFunctionCall2(ltq_regex,
+ PG_GETARG_DATUM(1),
+ PG_GETARG_DATUM(0)
+ ));
}
#include "utils/palloc.h"
#include "utils/builtins.h"
-typedef struct {
- uint8 len;
- char name[1];
-} ltree_level;
+typedef struct
+{
+ uint8 len;
+ char name[1];
+} ltree_level;
-#define LEVEL_HDRSIZE (sizeof(uint8))
+#define LEVEL_HDRSIZE (sizeof(uint8))
#define LEVEL_NEXT(x) ( (ltree_level*)( ((char*)(x)) + MAXALIGN(((ltree_level*)(x))->len + LEVEL_HDRSIZE) ) )
-typedef struct {
- int32 len;
- uint16 numlevel;
- char data[1];
-} ltree;
+typedef struct
+{
+ int32 len;
+ uint16 numlevel;
+ char data[1];
+} ltree;
#define LTREE_HDRSIZE MAXALIGN( sizeof(int32) + sizeof(uint16) )
#define LTREE_FIRST(x) ( (ltree_level*)( ((char*)(x))+LTREE_HDRSIZE ) )
/* lquery */
-typedef struct {
- int4 val;
- uint8 len;
- uint8 flag;
- char name[1];
-} lquery_variant;
+typedef struct
+{
+ int4 val;
+ uint8 len;
+ uint8 flag;
+ char name[1];
+} lquery_variant;
#define LVAR_HDRSIZE MAXALIGN(sizeof(uint8)*2 + sizeof(int4))
#define LVAR_NEXT(x) ( (lquery_variant*)( ((char*)(x)) + MAXALIGN(((lquery_variant*)(x))->len) + LVAR_HDRSIZE ) )
-#define LVAR_ANYEND 0x01
-#define LVAR_INCASE 0x02
+#define LVAR_ANYEND 0x01
+#define LVAR_INCASE 0x02
#define LVAR_SUBLEXEM 0x04
-typedef struct {
- uint16 totallen;
- uint16 flag;
- uint16 numvar;
- uint16 low;
- uint16 high;
- char variants[1];
-} lquery_level;
-
-#define LQL_HDRSIZE MAXALIGN( sizeof(uint16)*5 )
-#define LQL_NEXT(x) ( (lquery_level*)( ((char*)(x)) + MAXALIGN(((lquery_level*)(x))->totallen) ) )
+typedef struct
+{
+ uint16 totallen;
+ uint16 flag;
+ uint16 numvar;
+ uint16 low;
+ uint16 high;
+ char variants[1];
+} lquery_level;
+
+#define LQL_HDRSIZE MAXALIGN( sizeof(uint16)*5 )
+#define LQL_NEXT(x) ( (lquery_level*)( ((char*)(x)) + MAXALIGN(((lquery_level*)(x))->totallen) ) )
#define LQL_FIRST(x) ( (lquery_variant*)( ((char*)(x))+LQL_HDRSIZE ) )
#define LQL_NOT 0x10
#else
#define FLG_CANLOOKSIGN(x) ( ( (x) & ( LQL_NOT | LVAR_ANYEND | LVAR_SUBLEXEM | LVAR_INCASE ) ) == 0 )
#endif
-#define LQL_CANLOOKSIGN(x) FLG_CANLOOKSIGN( ((lquery_level*)(x))->flag )
-
-typedef struct {
- int32 len;
- uint16 numlevel;
- uint16 firstgood;
- uint16 flag;
- char data[1];
-} lquery;
+#define LQL_CANLOOKSIGN(x) FLG_CANLOOKSIGN( ((lquery_level*)(x))->flag )
-#define LQUERY_HDRSIZE MAXALIGN( sizeof(int32) + 3*sizeof(uint16) )
+typedef struct
+{
+ int32 len;
+ uint16 numlevel;
+ uint16 firstgood;
+ uint16 flag;
+ char data[1];
+} lquery;
+
+#define LQUERY_HDRSIZE MAXALIGN( sizeof(int32) + 3*sizeof(uint16) )
#define LQUERY_FIRST(x) ( (lquery_level*)( ((char*)(x))+LQUERY_HDRSIZE ) )
#define LQUERY_HASNOT 0x01
-#ifndef max
-#define max(a,b) ((a) > (b) ? (a) : (b))
+#ifndef max
+#define max(a,b) ((a) > (b) ? (a) : (b))
#endif
#ifndef min
-#define min(a,b) ((a) <= (b) ? (a) : (b))
+#define min(a,b) ((a) <= (b) ? (a) : (b))
#endif
#ifndef abs
-#define abs(a) ((a) < (0) ? -(a) : (a))
+#define abs(a) ((a) < (0) ? -(a) : (a))
#endif
#define ISALNUM(x) ( isalnum((unsigned int)(x)) || (x) == '_' )
*/
typedef struct ITEM
{
- int2 type;
- int2 left;
- int4 val;
+ int2 type;
+ int2 left;
+ int4 val;
uint8 flag;
- /* user-friendly value */
- uint8 length;
- uint16 distance;
-} ITEM;
+ /* user-friendly value */
+ uint8 length;
+ uint16 distance;
+} ITEM;
/*
*Storage:
- * (len)(size)(array of ITEM)(array of operand in user-friendly form)
+ * (len)(size)(array of ITEM)(array of operand in user-friendly form)
*/
typedef struct
{
- int4 len;
- int4 size;
- char data[1];
-} ltxtquery;
+ int4 len;
+ int4 size;
+ char data[1];
+} ltxtquery;
-#define HDRSIZEQT MAXALIGN( 2*sizeof(int4) )
-#define COMPUTESIZE(size,lenofoperand) ( HDRSIZEQT + size * sizeof(ITEM) + lenofoperand )
+#define HDRSIZEQT MAXALIGN( 2*sizeof(int4) )
+#define COMPUTESIZE(size,lenofoperand) ( HDRSIZEQT + size * sizeof(ITEM) + lenofoperand )
#define GETQUERY(x) (ITEM*)( (char*)(x)+HDRSIZEQT )
-#define GETOPERAND(x) ( (char*)GETQUERY(x) + ((ltxtquery*)x)->size * sizeof(ITEM) )
+#define GETOPERAND(x) ( (char*)GETQUERY(x) + ((ltxtquery*)x)->size * sizeof(ITEM) )
#define ISOPERATOR(x) ( (x)=='!' || (x)=='&' || (x)=='|' || (x)=='(' || (x)==')' )
-#define END 0
-#define ERR 1
-#define VAL 2
-#define OPR 3
-#define OPEN 4
-#define CLOSE 5
-#define VALTRUE 6 /* for stop words */
-#define VALFALSE 7
+#define END 0
+#define ERR 1
+#define VAL 2
+#define OPR 3
+#define OPEN 4
+#define CLOSE 5
+#define VALTRUE 6 /* for stop words */
+#define VALFALSE 7
/* use in array iterator */
-Datum ltree_isparent(PG_FUNCTION_ARGS);
-Datum ltree_risparent(PG_FUNCTION_ARGS);
-Datum ltq_regex(PG_FUNCTION_ARGS);
-Datum ltq_rregex(PG_FUNCTION_ARGS);
-Datum ltxtq_exec(PG_FUNCTION_ARGS);
-Datum ltxtq_rexec(PG_FUNCTION_ARGS);
-Datum _ltq_regex(PG_FUNCTION_ARGS);
-Datum _ltq_rregex(PG_FUNCTION_ARGS);
-Datum _ltxtq_exec(PG_FUNCTION_ARGS);
-Datum _ltxtq_rexec(PG_FUNCTION_ARGS);
-Datum _ltree_isparent(PG_FUNCTION_ARGS);
-Datum _ltree_risparent(PG_FUNCTION_ARGS);
+Datum ltree_isparent(PG_FUNCTION_ARGS);
+Datum ltree_risparent(PG_FUNCTION_ARGS);
+Datum ltq_regex(PG_FUNCTION_ARGS);
+Datum ltq_rregex(PG_FUNCTION_ARGS);
+Datum ltxtq_exec(PG_FUNCTION_ARGS);
+Datum ltxtq_rexec(PG_FUNCTION_ARGS);
+Datum _ltq_regex(PG_FUNCTION_ARGS);
+Datum _ltq_rregex(PG_FUNCTION_ARGS);
+Datum _ltxtq_exec(PG_FUNCTION_ARGS);
+Datum _ltxtq_rexec(PG_FUNCTION_ARGS);
+Datum _ltree_isparent(PG_FUNCTION_ARGS);
+Datum _ltree_risparent(PG_FUNCTION_ARGS);
/* Concatenation functions */
-Datum ltree_addltree(PG_FUNCTION_ARGS);
-Datum ltree_addtext(PG_FUNCTION_ARGS);
-Datum ltree_textadd(PG_FUNCTION_ARGS);
+Datum ltree_addltree(PG_FUNCTION_ARGS);
+Datum ltree_addtext(PG_FUNCTION_ARGS);
+Datum ltree_textadd(PG_FUNCTION_ARGS);
/* Util function */
-Datum ltree_in(PG_FUNCTION_ARGS);
+Datum ltree_in(PG_FUNCTION_ARGS);
bool ltree_execute(ITEM * curitem, void *checkval,
- bool calcnot, bool (*chkcond) (void *checkval, ITEM * val));
+ bool calcnot, bool (*chkcond) (void *checkval, ITEM * val));
-int ltree_compare(const ltree *a, const ltree *b);
-bool inner_isparent(const ltree *c, const ltree *p);
-bool compare_subnode( ltree_level *t, char *q, int len,
- int (*cmpptr)(const char *,const char *,size_t), bool anyend );
-ltree* lca_inner(ltree** a, int len);
+int ltree_compare(const ltree * a, const ltree * b);
+bool inner_isparent(const ltree * c, const ltree * p);
+bool compare_subnode(ltree_level * t, char *q, int len,
+ int (*cmpptr) (const char *, const char *, size_t), bool anyend);
+ltree *lca_inner(ltree ** a, int len);
-#define PG_GETARG_LTREE(x) ((ltree*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(x))))
+#define PG_GETARG_LTREE(x) ((ltree*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(x))))
#define PG_GETARG_LQUERY(x) ((lquery*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(x))))
#define PG_GETARG_LTXTQUERY(x) ((ltxtquery*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(x))))
#define BITBYTE 8
#define SIGLENINT 8
-#define SIGLEN ( sizeof(int4)*SIGLENINT )
+#define SIGLEN ( sizeof(int4)*SIGLENINT )
#define SIGLENBIT (SIGLEN*BITBYTE)
typedef unsigned char BITVEC[SIGLEN];
typedef unsigned char *BITVECP;
/*
* type of index key for ltree. Tree are combined B-Tree and R-Tree
* Storage:
- * Leaf pages
+ * Leaf pages
* (len)(flag)(ltree)
* Non-Leaf
- * (len)(flag)(sign)(left_ltree)(right_ltree)
+ * (len)(flag)(sign)(left_ltree)(right_ltree)
* ALLTRUE: (len)(flag)(left_ltree)(right_ltree)
- *
+ *
*/
-typedef struct {
- int4 len;
- uint32 flag;
- char data[1];
-} ltree_gist;
-
-#define LTG_ONENODE 0x01
-#define LTG_ALLTRUE 0x02
-#define LTG_NORIGHT 0x04
-
-#define LTG_HDRSIZE MAXALIGN( sizeof(int4) + sizeof(uint32) )
-#define LTG_SIGN(x) ( (BITVECP)( ((char*)(x))+LTG_HDRSIZE ) )
-#define LTG_NODE(x) ( (ltree*)( ((char*)(x))+LTG_HDRSIZE ) )
-#define LTG_ISONENODE(x) ( ((ltree_gist*)(x))->flag & LTG_ONENODE )
-#define LTG_ISALLTRUE(x) ( ((ltree_gist*)(x))->flag & LTG_ALLTRUE )
-#define LTG_ISNORIGHT(x) ( ((ltree_gist*)(x))->flag & LTG_NORIGHT )
+typedef struct
+{
+ int4 len;
+ uint32 flag;
+ char data[1];
+} ltree_gist;
+
+#define LTG_ONENODE 0x01
+#define LTG_ALLTRUE 0x02
+#define LTG_NORIGHT 0x04
+
+#define LTG_HDRSIZE MAXALIGN( sizeof(int4) + sizeof(uint32) )
+#define LTG_SIGN(x) ( (BITVECP)( ((char*)(x))+LTG_HDRSIZE ) )
+#define LTG_NODE(x) ( (ltree*)( ((char*)(x))+LTG_HDRSIZE ) )
+#define LTG_ISONENODE(x) ( ((ltree_gist*)(x))->flag & LTG_ONENODE )
+#define LTG_ISALLTRUE(x) ( ((ltree_gist*)(x))->flag & LTG_ALLTRUE )
+#define LTG_ISNORIGHT(x) ( ((ltree_gist*)(x))->flag & LTG_NORIGHT )
#define LTG_LNODE(x) ( (ltree*)( ( ((char*)(x))+LTG_HDRSIZE ) + ( LTG_ISALLTRUE(x) ? 0 : SIGLEN ) ) )
#define LTG_RENODE(x) ( (ltree*)( ((char*)LTG_LNODE(x)) + LTG_LNODE(x)->len) )
#define LTG_RNODE(x) ( LTG_ISNORIGHT(x) ? LTG_LNODE(x) : LTG_RENODE(x) )
-#define LTG_GETLNODE(x) ( LTG_ISONENODE(x) ? LTG_NODE(x) : LTG_LNODE(x) )
-#define LTG_GETRNODE(x) ( LTG_ISONENODE(x) ? LTG_NODE(x) : LTG_RNODE(x) )
+#define LTG_GETLNODE(x) ( LTG_ISONENODE(x) ? LTG_NODE(x) : LTG_LNODE(x) )
+#define LTG_GETRNODE(x) ( LTG_ISONENODE(x) ? LTG_NODE(x) : LTG_RNODE(x) )
/* GiST support for ltree[] */
-#define ASIGLENINT (2*SIGLENINT)
+#define ASIGLENINT (2*SIGLENINT)
#define ASIGLEN (sizeof(int4)*ASIGLENINT)
-#define ASIGLENBIT (ASIGLEN*BITBYTE)
+#define ASIGLENBIT (ASIGLEN*BITBYTE)
typedef unsigned char ABITVEC[ASIGLEN];
#define ALOOPBYTE(a) \
/* type of key is the same to ltree_gist */
#endif
-
/*
- * GiST support for ltree
+ * GiST support for ltree
* Teodor Sigaev <teodor@stack.net>
*/
#include "crc32.h"
-PG_FUNCTION_INFO_V1( ltree_gist_in );
-Datum ltree_gist_in(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( ltree_gist_out );
-Datum ltree_gist_out(PG_FUNCTION_ARGS);
+PG_FUNCTION_INFO_V1(ltree_gist_in);
+Datum ltree_gist_in(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ltree_gist_out);
+Datum ltree_gist_out(PG_FUNCTION_ARGS);
Datum
-ltree_gist_in(PG_FUNCTION_ARGS) {
- elog(ERROR,"Unimplemented");
+ltree_gist_in(PG_FUNCTION_ARGS)
+{
+ elog(ERROR, "Unimplemented");
PG_RETURN_DATUM(0);
}
Datum
-ltree_gist_out(PG_FUNCTION_ARGS) {
- elog(ERROR,"Unimplemented");
+ltree_gist_out(PG_FUNCTION_ARGS)
+{
+ elog(ERROR, "Unimplemented");
PG_RETURN_DATUM(0);
}
-PG_FUNCTION_INFO_V1( ltree_compress );
-Datum ltree_compress(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( ltree_decompress );
-Datum ltree_decompress(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( ltree_same );
-Datum ltree_same(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( ltree_union );
-Datum ltree_union(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( ltree_penalty );
-Datum ltree_penalty(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( ltree_picksplit );
-Datum ltree_picksplit(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( ltree_consistent );
-Datum ltree_consistent(PG_FUNCTION_ARGS);
+PG_FUNCTION_INFO_V1(ltree_compress);
+Datum ltree_compress(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ltree_decompress);
+Datum ltree_decompress(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ltree_same);
+Datum ltree_same(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ltree_union);
+Datum ltree_union(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ltree_penalty);
+Datum ltree_penalty(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ltree_picksplit);
+Datum ltree_picksplit(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ltree_consistent);
+Datum ltree_consistent(PG_FUNCTION_ARGS);
#define ISEQ(a,b) ( (a)->numlevel == (b)->numlevel && ltree_compare(a,b)==0 )
#define GETENTRY(vec,pos) ((ltree_gist *) DatumGetPointer(((GISTENTRY *) VARDATA(vec))[(pos)].key))
-Datum
-ltree_compress(PG_FUNCTION_ARGS) {
- GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
+Datum
+ltree_compress(PG_FUNCTION_ARGS)
+{
+ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
GISTENTRY *retval = entry;
- if ( entry->leafkey ) { /* ltree */
- ltree_gist *key;
- ltree *val = (ltree*)DatumGetPointer(PG_DETOAST_DATUM(entry->key));
- int4 len = LTG_HDRSIZE + val->len;
+ if (entry->leafkey)
+ { /* ltree */
+ ltree_gist *key;
+ ltree *val = (ltree *) DatumGetPointer(PG_DETOAST_DATUM(entry->key));
+ int4 len = LTG_HDRSIZE + val->len;
- key = (ltree_gist*)palloc( len );
+ key = (ltree_gist *) palloc(len);
key->len = len;
key->flag = LTG_ONENODE;
- memcpy( (void*)LTG_NODE(key), (void*)val, val->len);
+ memcpy((void *) LTG_NODE(key), (void *) val, val->len);
- if ( PointerGetDatum(val) != entry->key )
+ if (PointerGetDatum(val) != entry->key)
pfree(val);
- retval = (GISTENTRY*)palloc( sizeof(GISTENTRY) );
+ retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
gistentryinit(*retval, PointerGetDatum(key),
- entry->rel, entry->page,
- entry->offset, key->len, FALSE);
+ entry->rel, entry->page,
+ entry->offset, key->len, FALSE);
}
PG_RETURN_POINTER(retval);
}
-Datum
-ltree_decompress(PG_FUNCTION_ARGS) {
- GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
- ltree_gist *key = (ltree_gist*)DatumGetPointer( PG_DETOAST_DATUM(entry->key) );
+Datum
+ltree_decompress(PG_FUNCTION_ARGS)
+{
+ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
+ ltree_gist *key = (ltree_gist *) DatumGetPointer(PG_DETOAST_DATUM(entry->key));
+
+ if (PointerGetDatum(key) != entry->key)
+ {
+ GISTENTRY *retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
- if ( PointerGetDatum(key) != entry->key ) {
- GISTENTRY *retval = (GISTENTRY*)palloc(sizeof(GISTENTRY));
gistentryinit(*retval, PointerGetDatum(key),
- entry->rel, entry->page,
- entry->offset, key->len, FALSE);
+ entry->rel, entry->page,
+ entry->offset, key->len, FALSE);
PG_RETURN_POINTER(retval);
}
- PG_RETURN_POINTER(entry);
+ PG_RETURN_POINTER(entry);
}
-Datum
-ltree_same(PG_FUNCTION_ARGS) {
- ltree_gist* a=(ltree_gist*)PG_GETARG_POINTER(0);
- ltree_gist* b=(ltree_gist*)PG_GETARG_POINTER(1);
- bool *result = (bool *)PG_GETARG_POINTER(2);
+Datum
+ltree_same(PG_FUNCTION_ARGS)
+{
+ ltree_gist *a = (ltree_gist *) PG_GETARG_POINTER(0);
+ ltree_gist *b = (ltree_gist *) PG_GETARG_POINTER(1);
+ bool *result = (bool *) PG_GETARG_POINTER(2);
*result = false;
- if ( LTG_ISONENODE(a) != LTG_ISONENODE(b) )
- PG_RETURN_POINTER(result);
-
- if ( LTG_ISONENODE(a) ) {
- *result = ( ISEQ(LTG_NODE(a), LTG_NODE(b)) ) ? true : false;
- } else {
- int4 i;
- BITVECP sa=LTG_SIGN(a), sb=LTG_SIGN(b);
-
- if ( LTG_ISALLTRUE(a) != LTG_ISALLTRUE(b) )
- PG_RETURN_POINTER(result);
-
- if ( !ISEQ(LTG_LNODE(a), LTG_LNODE(b)) )
- PG_RETURN_POINTER(result);
- if ( !ISEQ(LTG_RNODE(a), LTG_RNODE(b)) )
+ if (LTG_ISONENODE(a) != LTG_ISONENODE(b))
+ PG_RETURN_POINTER(result);
+
+ if (LTG_ISONENODE(a))
+ *result = (ISEQ(LTG_NODE(a), LTG_NODE(b))) ? true : false;
+ else
+ {
+ int4 i;
+ BITVECP sa = LTG_SIGN(a),
+ sb = LTG_SIGN(b);
+
+ if (LTG_ISALLTRUE(a) != LTG_ISALLTRUE(b))
+ PG_RETURN_POINTER(result);
+
+ if (!ISEQ(LTG_LNODE(a), LTG_LNODE(b)))
+ PG_RETURN_POINTER(result);
+ if (!ISEQ(LTG_RNODE(a), LTG_RNODE(b)))
PG_RETURN_POINTER(result);
*result = true;
- if ( !LTG_ISALLTRUE(a) )
+ if (!LTG_ISALLTRUE(a))
LOOPBYTE(
- if ( sa[i] != sb[i] ) {
- *result = false;
- break;
- }
- );
+ if (sa[i] != sb[i])
+ {
+ *result = false;
+ break;
+ }
+ );
}
-
- PG_RETURN_POINTER(result);
+
+ PG_RETURN_POINTER(result);
}
static void
-hashing(BITVECP sign, ltree *t) {
- int tlen = t->numlevel;
+hashing(BITVECP sign, ltree * t)
+{
+ int tlen = t->numlevel;
ltree_level *cur = LTREE_FIRST(t);
- int hash;
+ int hash;
- while(tlen > 0) {
- hash = ltree_crc32_sz( cur->name, cur->len );
- HASH( sign, hash );
+ while (tlen > 0)
+ {
+ hash = ltree_crc32_sz(cur->name, cur->len);
+ HASH(sign, hash);
cur = LEVEL_NEXT(cur);
tlen--;
}
}
-Datum
-ltree_union(PG_FUNCTION_ARGS) {
- bytea *entryvec = (bytea *) PG_GETARG_POINTER(0);
- int *size = (int *) PG_GETARG_POINTER(1);
- BITVEC base;
- int4 len = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY);
- int4 i,j;
- ltree_gist *result,*cur;
- ltree *left=NULL, *right=NULL, *curtree;
- bool isalltrue = false;
- bool isleqr;
-
- MemSet( (void*)base, 0, sizeof(BITVEC) );
- for(j=0;j<len;j++) {
+Datum
+ltree_union(PG_FUNCTION_ARGS)
+{
+ bytea *entryvec = (bytea *) PG_GETARG_POINTER(0);
+ int *size = (int *) PG_GETARG_POINTER(1);
+ BITVEC base;
+ int4 len = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY);
+ int4 i,
+ j;
+ ltree_gist *result,
+ *cur;
+ ltree *left = NULL,
+ *right = NULL,
+ *curtree;
+ bool isalltrue = false;
+ bool isleqr;
+
+ MemSet((void *) base, 0, sizeof(BITVEC));
+ for (j = 0; j < len; j++)
+ {
cur = GETENTRY(entryvec, j);
- if ( LTG_ISONENODE(cur) ) {
+ if (LTG_ISONENODE(cur))
+ {
curtree = LTG_NODE(cur);
- hashing(base,curtree);
- if ( !left || ltree_compare( left, curtree ) > 0 )
- left = curtree;
- if ( !right || ltree_compare( right, curtree ) < 0 )
+ hashing(base, curtree);
+ if (!left || ltree_compare(left, curtree) > 0)
+ left = curtree;
+ if (!right || ltree_compare(right, curtree) < 0)
right = curtree;
- } else {
- if ( isalltrue || LTG_ISALLTRUE(cur) )
+ }
+ else
+ {
+ if (isalltrue || LTG_ISALLTRUE(cur))
isalltrue = true;
- else {
- BITVECP sc=LTG_SIGN(cur);
+ else
+ {
+ BITVECP sc = LTG_SIGN(cur);
+
LOOPBYTE(
- ((unsigned char*)base)[i] |= sc[i];
+ ((unsigned char *) base)[i] |= sc[i];
);
}
curtree = LTG_LNODE(cur);
- if ( !left || ltree_compare( left, curtree ) > 0 )
- left = curtree;
+ if (!left || ltree_compare(left, curtree) > 0)
+ left = curtree;
curtree = LTG_RNODE(cur);
- if ( !right || ltree_compare( right, curtree ) < 0 )
+ if (!right || ltree_compare(right, curtree) < 0)
right = curtree;
- }
+ }
}
-
- if ( isalltrue == false ) {
+
+ if (isalltrue == false)
+ {
isalltrue = true;
LOOPBYTE(
- if ( ((unsigned char*)base)[i] != 0xff ) {
- isalltrue = false;
- break;
- }
- );
+ if (((unsigned char *) base)[i] != 0xff)
+ {
+ isalltrue = false;
+ break;
+ }
+ );
}
- isleqr = ( left==right || ISEQ(left,right) ) ? true : false;
- *size = LTG_HDRSIZE + ( (isalltrue) ? 0 : SIGLEN ) + left->len + ( (isleqr) ? 0 : right->len );
+ isleqr = (left == right || ISEQ(left, right)) ? true : false;
+ *size = LTG_HDRSIZE + ((isalltrue) ? 0 : SIGLEN) + left->len + ((isleqr) ? 0 : right->len);
- result = (ltree_gist*)palloc( *size );
+ result = (ltree_gist *) palloc(*size);
result->len = *size;
result->flag = 0;
- if ( isalltrue )
+ if (isalltrue)
result->flag |= LTG_ALLTRUE;
else
- memcpy( (void*)LTG_SIGN(result), base, SIGLEN );
+ memcpy((void *) LTG_SIGN(result), base, SIGLEN);
- memcpy( (void*)LTG_LNODE(result), (void*)left, left->len );
- if ( isleqr )
+ memcpy((void *) LTG_LNODE(result), (void *) left, left->len);
+ if (isleqr)
result->flag |= LTG_NORIGHT;
else
- memcpy( (void*)LTG_RNODE(result), (void*)right, right->len );
+ memcpy((void *) LTG_RNODE(result), (void *) right, right->len);
- PG_RETURN_POINTER(result);
+ PG_RETURN_POINTER(result);
}
-Datum
-ltree_penalty(PG_FUNCTION_ARGS) {
- ltree_gist *origval = (ltree_gist*)DatumGetPointer( ( (GISTENTRY *)PG_GETARG_POINTER(0) )->key );
- ltree_gist *newval = (ltree_gist*)DatumGetPointer( ( (GISTENTRY *)PG_GETARG_POINTER(1) )->key );
- float *penalty = (float *) PG_GETARG_POINTER(2);
- int4 cmpr,cmpl;
+Datum
+ltree_penalty(PG_FUNCTION_ARGS)
+{
+ ltree_gist *origval = (ltree_gist *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(0))->key);
+ ltree_gist *newval = (ltree_gist *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(1))->key);
+ float *penalty = (float *) PG_GETARG_POINTER(2);
+ int4 cmpr,
+ cmpl;
- cmpl = ltree_compare( LTG_GETLNODE(origval), LTG_GETLNODE(newval) );
- cmpr = ltree_compare( LTG_GETRNODE(newval), LTG_GETRNODE(origval));
+ cmpl = ltree_compare(LTG_GETLNODE(origval), LTG_GETLNODE(newval));
+ cmpr = ltree_compare(LTG_GETRNODE(newval), LTG_GETRNODE(origval));
- *penalty = max( cmpl, 0 ) + max( cmpr, 0 );
+ *penalty = max(cmpl, 0) + max(cmpr, 0);
PG_RETURN_POINTER(penalty);
}
/* used for sorting */
-typedef struct rix {
- int index;
- ltree *r;
-} RIX;
+typedef struct rix
+{
+ int index;
+ ltree *r;
+} RIX;
static int
-treekey_cmp(const void *a, const void *b) {
+treekey_cmp(const void *a, const void *b)
+{
return ltree_compare(
- ((RIX *) a)->r,
- ((RIX *) b)->r
+ ((RIX *) a)->r,
+ ((RIX *) b)->r
);
}
-Datum
-ltree_picksplit(PG_FUNCTION_ARGS) {
- bytea *entryvec = (bytea*) PG_GETARG_POINTER(0);
- GIST_SPLITVEC *v = (GIST_SPLITVEC*) PG_GETARG_POINTER(1);
+Datum
+ltree_picksplit(PG_FUNCTION_ARGS)
+{
+ bytea *entryvec = (bytea *) PG_GETARG_POINTER(0);
+ GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1);
OffsetNumber j;
- int4 i;
- RIX *array;
+ int4 i;
+ RIX *array;
OffsetNumber maxoff;
- int nbytes;
- int size;
- ltree *lu_l,*lu_r, *ru_l, *ru_r;
- ltree_gist *lu, *ru;
- BITVEC ls,rs;
- bool lisat=false, risat=false, isleqr;
-
- memset( (void*)ls,0,sizeof(BITVEC) );
- memset( (void*)rs,0,sizeof(BITVEC) );
+ int nbytes;
+ int size;
+ ltree *lu_l,
+ *lu_r,
+ *ru_l,
+ *ru_r;
+ ltree_gist *lu,
+ *ru;
+ BITVEC ls,
+ rs;
+ bool lisat = false,
+ risat = false,
+ isleqr;
+
+ memset((void *) ls, 0, sizeof(BITVEC));
+ memset((void *) rs, 0, sizeof(BITVEC));
maxoff = ((VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY)) - 1;
nbytes = (maxoff + 2) * sizeof(OffsetNumber);
v->spl_left = (OffsetNumber *) palloc(nbytes);
v->spl_nleft = 0;
v->spl_nright = 0;
array = (RIX *) palloc(sizeof(RIX) * (maxoff + 1));
-
+
/* copy the data into RIXes, and sort the RIXes */
- for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j)) {
+ for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j))
+ {
array[j].index = j;
- lu = GETENTRY( entryvec, j ); /* use as tmp val */
+ lu = GETENTRY(entryvec, j); /* use as tmp val */
array[j].r = LTG_GETLNODE(lu);
}
qsort((void *) &array[FirstOffsetNumber], maxoff - FirstOffsetNumber + 1,
- sizeof(RIX), treekey_cmp);
+ sizeof(RIX), treekey_cmp);
lu_l = lu_r = ru_l = ru_r = NULL;
- for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j)) {
- lu = GETENTRY( entryvec, array[j].index ); /* use as tmp val */
- if (j <= (maxoff - FirstOffsetNumber + 1) / 2) {
+ for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j))
+ {
+ lu = GETENTRY(entryvec, array[j].index); /* use as tmp val */
+ if (j <= (maxoff - FirstOffsetNumber + 1) / 2)
+ {
v->spl_left[v->spl_nleft] = array[j].index;
v->spl_nleft++;
- if ( lu_r==NULL || ltree_compare( LTG_GETRNODE(lu), lu_r ) > 0 )
+ if (lu_r == NULL || ltree_compare(LTG_GETRNODE(lu), lu_r) > 0)
lu_r = LTG_GETRNODE(lu);
- if ( LTG_ISONENODE(lu) )
- hashing(ls,LTG_NODE(lu));
- else {
- if ( lisat || LTG_ISALLTRUE(lu) )
+ if (LTG_ISONENODE(lu))
+ hashing(ls, LTG_NODE(lu));
+ else
+ {
+ if (lisat || LTG_ISALLTRUE(lu))
lisat = true;
- else {
- BITVECP sc=LTG_SIGN(lu);
+ else
+ {
+ BITVECP sc = LTG_SIGN(lu);
+
LOOPBYTE(
- ((unsigned char*)ls)[i] |= sc[i];
+ ((unsigned char *) ls)[i] |= sc[i];
);
}
}
- } else {
+ }
+ else
+ {
v->spl_right[v->spl_nright] = array[j].index;
v->spl_nright++;
- if ( ru_r==NULL || ltree_compare( LTG_GETRNODE(lu), ru_r ) > 0 )
+ if (ru_r == NULL || ltree_compare(LTG_GETRNODE(lu), ru_r) > 0)
ru_r = LTG_GETRNODE(lu);
- if ( LTG_ISONENODE(lu) )
- hashing(rs,LTG_NODE(lu));
- else {
- if ( risat || LTG_ISALLTRUE(lu) )
+ if (LTG_ISONENODE(lu))
+ hashing(rs, LTG_NODE(lu));
+ else
+ {
+ if (risat || LTG_ISALLTRUE(lu))
risat = true;
- else {
- BITVECP sc=LTG_SIGN(lu);
+ else
+ {
+ BITVECP sc = LTG_SIGN(lu);
+
LOOPBYTE(
- ((unsigned char*)rs)[i] |= sc[i];
+ ((unsigned char *) rs)[i] |= sc[i];
);
}
}
}
}
-
- if ( lisat == false ) {
+
+ if (lisat == false)
+ {
lisat = true;
LOOPBYTE(
- if ( ((unsigned char*)ls)[i] != 0xff ) {
- lisat = false;
- break;
- }
- );
+ if (((unsigned char *) ls)[i] != 0xff)
+ {
+ lisat = false;
+ break;
+ }
+ );
}
- if ( risat == false ) {
+ if (risat == false)
+ {
risat = true;
LOOPBYTE(
- if ( ((unsigned char*)rs)[i] != 0xff ) {
- risat = false;
- break;
- }
- );
+ if (((unsigned char *) rs)[i] != 0xff)
+ {
+ risat = false;
+ break;
+ }
+ );
}
- lu_l = LTG_GETLNODE( GETENTRY( entryvec, array[FirstOffsetNumber].index ) );
- isleqr = ( lu_l==lu_r || ISEQ(lu_l,lu_r) ) ? true : false;
- size = LTG_HDRSIZE + ( (lisat) ? 0 : SIGLEN ) + lu_l->len + ( (isleqr) ? 0 : lu_r->len );
- lu = (ltree_gist*)palloc( size );
+ lu_l = LTG_GETLNODE(GETENTRY(entryvec, array[FirstOffsetNumber].index));
+ isleqr = (lu_l == lu_r || ISEQ(lu_l, lu_r)) ? true : false;
+ size = LTG_HDRSIZE + ((lisat) ? 0 : SIGLEN) + lu_l->len + ((isleqr) ? 0 : lu_r->len);
+ lu = (ltree_gist *) palloc(size);
lu->len = size;
lu->flag = 0;
- if ( lisat )
+ if (lisat)
lu->flag |= LTG_ALLTRUE;
else
- memcpy( (void*)LTG_SIGN(lu), ls, SIGLEN );
- memcpy( (void*)LTG_LNODE(lu), (void*)lu_l, lu_l->len );
- if ( isleqr )
+ memcpy((void *) LTG_SIGN(lu), ls, SIGLEN);
+ memcpy((void *) LTG_LNODE(lu), (void *) lu_l, lu_l->len);
+ if (isleqr)
lu->flag |= LTG_NORIGHT;
else
- memcpy( (void*)LTG_RNODE(lu), (void*)lu_r, lu_r->len );
+ memcpy((void *) LTG_RNODE(lu), (void *) lu_r, lu_r->len);
- ru_l = LTG_GETLNODE( GETENTRY( entryvec, array[ 1 + ((maxoff - FirstOffsetNumber + 1) / 2) ].index ) );
- isleqr = ( ru_l==ru_r || ISEQ(ru_l,ru_r) ) ? true : false;
- size = LTG_HDRSIZE + ( (risat) ? 0 : SIGLEN ) + ru_l->len + ( (isleqr) ? 0 : ru_r->len );
- ru = (ltree_gist*)palloc( size );
+ ru_l = LTG_GETLNODE(GETENTRY(entryvec, array[1 + ((maxoff - FirstOffsetNumber + 1) / 2)].index));
+ isleqr = (ru_l == ru_r || ISEQ(ru_l, ru_r)) ? true : false;
+ size = LTG_HDRSIZE + ((risat) ? 0 : SIGLEN) + ru_l->len + ((isleqr) ? 0 : ru_r->len);
+ ru = (ltree_gist *) palloc(size);
ru->len = size;
ru->flag = 0;
- if ( risat )
+ if (risat)
ru->flag |= LTG_ALLTRUE;
else
- memcpy( (void*)LTG_SIGN(ru), rs, SIGLEN );
- memcpy( (void*)LTG_LNODE(ru), (void*)ru_l, ru_l->len );
- if ( isleqr )
+ memcpy((void *) LTG_SIGN(ru), rs, SIGLEN);
+ memcpy((void *) LTG_LNODE(ru), (void *) ru_l, ru_l->len);
+ if (isleqr)
ru->flag |= LTG_NORIGHT;
else
- memcpy( (void*)LTG_RNODE(ru), (void*)ru_r, ru_r->len );
+ memcpy((void *) LTG_RNODE(ru), (void *) ru_r, ru_r->len);
pfree(array);
v->spl_ldatum = PointerGetDatum(lu);
}
static bool
-gist_isparent(ltree_gist *key, ltree *query) {
- int4 numlevel = query->numlevel;
- int i;
-
- for(i=query->numlevel;i>=0;i--) {
- query->numlevel=i;
- if ( ltree_compare(query,LTG_GETLNODE(key)) >=0 && ltree_compare(query,LTG_GETRNODE(key)) <= 0 ) {
+gist_isparent(ltree_gist * key, ltree * query)
+{
+ int4 numlevel = query->numlevel;
+ int i;
+
+ for (i = query->numlevel; i >= 0; i--)
+ {
+ query->numlevel = i;
+ if (ltree_compare(query, LTG_GETLNODE(key)) >= 0 && ltree_compare(query, LTG_GETRNODE(key)) <= 0)
+ {
query->numlevel = numlevel;
return true;
}
}
static bool
-gist_ischild(ltree_gist *key, ltree *query) {
- ltree *left = LTG_GETLNODE(key);
- ltree *right = LTG_GETRNODE(key);
- int4 numlevelL = left->numlevel;
- int4 numlevelR = right->numlevel;
- bool res = true;
-
- if ( numlevelL > query->numlevel )
+gist_ischild(ltree_gist * key, ltree * query)
+{
+ ltree *left = LTG_GETLNODE(key);
+ ltree *right = LTG_GETRNODE(key);
+ int4 numlevelL = left->numlevel;
+ int4 numlevelR = right->numlevel;
+ bool res = true;
+
+ if (numlevelL > query->numlevel)
left->numlevel = query->numlevel;
- if ( ltree_compare(query,left) < 0 )
+ if (ltree_compare(query, left) < 0)
res = false;
- if ( numlevelR > query->numlevel )
+ if (numlevelR > query->numlevel)
right->numlevel = query->numlevel;
- if ( res && ltree_compare(query,right) > 0 )
+ if (res && ltree_compare(query, right) > 0)
res = false;
left->numlevel = numlevelL;
}
static bool
-gist_qe(ltree_gist *key, lquery* query) {
- lquery_level *curq = LQUERY_FIRST(query);
- BITVECP sign = LTG_SIGN(key);
- int qlen = query->numlevel;
+gist_qe(ltree_gist * key, lquery * query)
+{
+ lquery_level *curq = LQUERY_FIRST(query);
+ BITVECP sign = LTG_SIGN(key);
+ int qlen = query->numlevel;
- if ( LTG_ISALLTRUE(key) )
+ if (LTG_ISALLTRUE(key))
return true;
- while( qlen>0 ) {
- if ( curq->numvar && LQL_CANLOOKSIGN(curq) ) {
- bool isexist=false;
- int vlen = curq->numvar;
+ while (qlen > 0)
+ {
+ if (curq->numvar && LQL_CANLOOKSIGN(curq))
+ {
+ bool isexist = false;
+ int vlen = curq->numvar;
lquery_variant *curv = LQL_FIRST(curq);
- while( vlen>0 ) {
- if ( GETBIT( sign, HASHVAL( curv->val ) ) ) {
- isexist=true;
+
+ while (vlen > 0)
+ {
+ if (GETBIT(sign, HASHVAL(curv->val)))
+ {
+ isexist = true;
break;
}
curv = LVAR_NEXT(curv);
vlen--;
}
- if ( !isexist )
- return false;
+ if (!isexist)
+ return false;
}
curq = LQL_NEXT(curq);
}
static int
-gist_tqcmp(ltree* t, lquery* q) {
+gist_tqcmp(ltree * t, lquery * q)
+{
ltree_level *al = LTREE_FIRST(t);
lquery_level *ql = LQUERY_FIRST(q);
lquery_variant *bl;
- int an = t->numlevel;
- int bn = q->firstgood;
- int res = 0;
+ int an = t->numlevel;
+ int bn = q->firstgood;
+ int res = 0;
- while( an>0 && bn>0 ) {
+ while (an > 0 && bn > 0)
+ {
bl = LQL_FIRST(ql);
- if ( (res = strncmp( al->name, bl->name, min(al->len, bl->len))) == 0 ) {
- if ( al->len != bl->len )
+ if ((res = strncmp(al->name, bl->name, min(al->len, bl->len))) == 0)
+ {
+ if (al->len != bl->len)
return al->len - bl->len;
- } else
+ }
+ else
&n