1 /*-------------------------------------------------------------------------
4 * Special functions for arrays.
6 * Copyright (c) 1994, Regents of the University of California
10 * $Header: /cvsroot/pgsql/src/backend/utils/adt/arrayfuncs.c,v 1.47 1999/07/17 20:17:53 momjian Exp $
12 *-------------------------------------------------------------------------
20 #include "catalog/catalog.h"
21 #include "catalog/pg_type.h"
23 #include "libpq/be-fsstubs.h"
24 #include "libpq/libpq-fs.h"
25 #include "storage/fd.h"
26 #include "utils/array.h"
27 #include "utils/memutils.h"
28 #include "utils/syscache.h"
32 /* An array has the following internal structure:
33 * <nbytes> - total number of bytes
34 * <ndim> - number of dimensions of the array
35 * <flags> - bit mask of flags
36 * <dim> - size of each array axis
37 * <dim_lower> - lower boundary of each dimension
38 * <actual data> - whatever is the stored data
41 /*-=-=--=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-*/
42 static int _ArrayCount(char *str, int *dim, int typdelim);
43 static char *_ReadArrayStr(char *arrayStr, int nitems, int ndim, int *dim,
44 FmgrInfo *inputproc, Oid typelem, int32 typmod,
45 char typdelim, int typlen, bool typbyval,
46 char typalign, int *nbytes);
49 static char *_ReadLOArray(char *str, int *nbytes, int *fd, bool *chunkFlag,
50 int ndim, int *dim, int baseSize);
53 static void _CopyArrayEls(char **values, char *p, int nitems, int typlen,
54 char typalign, bool typbyval);
55 static void system_cache_lookup(Oid element_type, bool input, int *typlen,
56 bool *typbyval, char *typdelim, Oid *typelem, Oid *proc,
58 static Datum _ArrayCast(char *value, bool byval, int len);
61 static char *_AdvanceBy1word(char *str, char **word);
64 static void _ArrayRange(int *st, int *endp, int bsize, char *destPtr,
65 ArrayType *array, int from);
66 static int _ArrayClipCount(int *stI, int *endpI, ArrayType *array);
67 static void _LOArrayRange(int *st, int *endp, int bsize, int srcfd,
68 int destfd, ArrayType *array, int isSrcLO, bool *isNull);
69 static void _ReadArray(int *st, int *endp, int bsize, int srcfd, int destfd,
70 ArrayType *array, int isDestLO, bool *isNull);
71 static int ArrayCastAndSet(char *src, bool typbyval, int typlen, char *dest);
72 static int SanityCheckInput(int ndim, int n, int *dim, int *lb, int *indx);
73 static int array_read(char *destptr, int eltsize, int nitems, char *srcptr);
74 static char *array_seek(char *ptr, int eltsize, int nitems);
76 /*---------------------------------------------------------------------
78 * converts an array from the external format in "string" to
81 * the internal representation of the input array
82 *--------------------------------------------------------------------
85 array_in(char *string, /* input array in external form */
86 Oid element_type, /* type OID of an array element */
104 ArrayType *retval = NULL;
110 system_cache_lookup(element_type, true, &typlen, &typbyval, &typdelim,
111 &typelem, &typinput, &typalign);
113 fmgr_info(typinput, &inputproc);
115 string_save = (char *) palloc(strlen(string) + 3);
116 strcpy(string_save, string);
118 /* --- read array dimensions ---------- */
121 for (ndim = 0; !done;)
128 if ((r = (char *) strchr(p, ':')) == (char *) NULL)
133 lBound[ndim] = atoi(p);
136 for (q = p; isdigit(*q); q++);
138 elog(ERROR, "array_in: missing ']' in array declaration");
141 if ((dim[ndim] < 0) || (lBound[ndim] < 0))
142 elog(ERROR, "array_in: array dimensions need to be positive");
143 dim[ndim] = dim[ndim] - lBound[ndim] + 1;
145 elog(ERROR, "array_in: upper_bound cannot be < lower_bound");
157 ndim = _ArrayCount(p, dim, typdelim);
158 for (i = 0; i < ndim; lBound[i++] = 1);
161 elog(ERROR, "array_in: Need to specify dimension");
167 if (strncmp(p, ASSGN, strlen(ASSGN)))
168 elog(ERROR, "array_in: missing assignment operator");
175 printf("array_in- ndim %d (", ndim);
176 for (i = 0; i < ndim; i++)
178 printf(" %d", dim[i]);
180 printf(") for %s\n", string);
183 nitems = getNitems(ndim, dim);
186 char *emptyArray = palloc(sizeof(ArrayType));
188 MemSet(emptyArray, 0, sizeof(ArrayType));
189 *(int32 *) emptyArray = sizeof(ArrayType);
195 /* array not a large object */
196 dataPtr = (char *) _ReadArrayStr(p, nitems, ndim, dim, &inputproc, typelem,
197 typmod, typdelim, typlen, typbyval, typalign,
199 nbytes += ARR_OVERHEAD(ndim);
200 retval = (ArrayType *) palloc(nbytes);
201 MemSet(retval, 0, nbytes);
202 memmove(retval, (char *) &nbytes, sizeof(int));
203 memmove((char *) ARR_NDIM_PTR(retval), (char *) &ndim, sizeof(int));
204 SET_LO_FLAG(false, retval);
205 memmove((char *) ARR_DIMS(retval), (char *) dim, ndim * sizeof(int));
206 memmove((char *) ARR_LBOUND(retval), (char *) lBound,
210 * dataPtr is an array of arbitraystuff even though its type is
211 * char* cast to char** to pass to _CopyArrayEls for now - jolly
213 _CopyArrayEls((char **) dataPtr,
214 ARR_DATA_PTR(retval), nitems,
215 typlen, typalign, typbyval);
222 bool chunked = false;
224 dataPtr = _ReadLOArray(p, &bytes, &dummy, &chunked, ndim,
226 nbytes = bytes + ARR_OVERHEAD(ndim);
227 retval = (ArrayType *) palloc(nbytes);
228 MemSet(retval, 0, nbytes);
229 memmove(retval, (char *) &nbytes, sizeof(int));
230 memmove((char *) ARR_NDIM_PTR(retval), (char *) &ndim, sizeof(int));
231 SET_LO_FLAG(true, retval);
232 SET_CHUNK_FLAG(chunked, retval);
233 memmove((char *) ARR_DIMS(retval), (char *) dim, ndim * sizeof(int));
234 memmove((char *) ARR_LBOUND(retval), (char *) lBound, ndim * sizeof(int));
235 memmove(ARR_DATA_PTR(retval), dataPtr, bytes);
237 elog(ERROR, "large object arrays not supported");
240 return (char *) retval;
243 /*-----------------------------------------------------------------------------
245 * Counts the number of dimensions and the *dim array for an array string.
246 * The syntax for array input is C-like nested curly braces
247 *-----------------------------------------------------------------------------
250 _ArrayCount(char *str, int *dim, int typdelim)
256 bool scanning_string = false;
257 bool eoArray = false;
260 for (i = 0; i < MAXDIM; ++i)
261 temp[i] = dim[i] = 0;
263 if (strncmp(str, "{}", 2) == 0)
267 while (eoArray != true)
276 /* skip escaped characters (\ and ") inside strings */
277 if (scanning_string && *(q + 1))
283 * Signal a premature end of the string. DZ -
286 elog(ERROR, "malformed array constant: %s", str);
289 scanning_string = !scanning_string;
292 if (!scanning_string)
294 temp[nest_level] = 0;
299 if (!scanning_string)
305 temp[nest_level - 1]++;
307 eoArray = done = true;
313 if (*q == typdelim && !scanning_string)
326 for (i = 0; i < ndim; ++i)
332 /*---------------------------------------------------------------------------
334 * parses the array string pointed by "arrayStr" and converts it in the
335 * internal format. The external format expected is like C array
336 * declaration. Unspecified elements are initialized to zero for fixed length
337 * base types and to empty varlena structures for variable length base
340 * returns the internal representation of the array elements
341 * nbytes is set to the size of the array in its internal representation.
342 *---------------------------------------------------------------------------
345 _ReadArrayStr(char *arrayStr,
349 FmgrInfo *inputproc, /* function used for the
365 bool scanning_string = false;
368 bool eoArray = false;
370 mda_get_prod(ndim, dim, prod);
371 for (i = 0; i < ndim; indx[i++] = 0);
372 /* read array enclosed within {} */
373 values = (char **) palloc(nitems * sizeof(char *));
374 MemSet(values, 0, nitems * sizeof(char *));
387 /* Crunch the string on top of the backslash. */
388 for (r = q; *r != '\0'; r++)
392 if (!scanning_string)
396 p++; /* get p past first doublequote */
400 scanning_string = !scanning_string;
403 if (!scanning_string)
407 if (nest_level > ndim)
408 elog(ERROR, "array_in: illformed array constant");
409 indx[nest_level - 1] = 0;
414 if (!scanning_string)
417 i = tuple2linear(ndim, indx, prod);
420 eoArray = done = true;
424 indx[nest_level - 1]++;
429 if (*q == typdelim && !scanning_string)
432 i = tuple2linear(ndim, indx, prod);
443 elog(ERROR, "array_in: illformed array constant");
444 values[i] = (*fmgr_faddr(inputproc)) (p, typelem, typmod);
449 * if not at the end of the array skip white space
459 *nbytes = nitems * typlen;
461 for (i = 0; i < nitems; i++)
464 values[i] = palloc(typlen);
465 MemSet(values[i], 0, typlen);
470 for (i = 0, *nbytes = 0; i < nitems; i++)
475 *nbytes += DOUBLEALIGN(*(int32 *) values[i]);
477 *nbytes += INTALIGN(*(int32 *) values[i]);
481 *nbytes += sizeof(int32);
482 values[i] = palloc(sizeof(int32));
483 *(int32 *) values[i] = sizeof(int32);
487 return (char *) values;
491 /*----------------------------------------------------------------------------
492 * Read data about an array to be stored as a large object
493 *----------------------------------------------------------------------------
497 _ReadLOArray(char *str,
512 str = _AdvanceBy1word(str, &inputfile);
518 str = _AdvanceBy1word(str, &word);
520 if (!strcmp(word, "-chunk"))
523 elog(ERROR, "array_in: access pattern file required");
524 str = _AdvanceBy1word(str, &accessfile);
526 else if (!strcmp(word, "-noreorg"))
529 elog(ERROR, "array_in: chunk file required");
530 str = _AdvanceBy1word(str, &chunkfile);
533 elog(ERROR, "usage: <input file> -chunk DEFAULT/<access pattern file> -invert/-native [-noreorg <chunk file>]");
536 if (inputfile == NULL)
537 elog(ERROR, "array_in: missing file name");
538 lobjId = lo_creat(0);
539 *fd = lo_open(lobjId, INV_READ);
541 elog(ERROR, "Large object create failed");
543 *nbytes = strlen(retStr) + 2;
550 if ((afd = AllocateFile(accessfile, "r")) == NULL)
552 if ((afd = AllocateFile(accessfile, "r")) == NULL)
554 elog(ERROR, "unable to open access pattern file");
556 retStr = _ChunkArray(*fd, afd, ndim, dim, baseSize, nbytes,
566 _CopyArrayEls(char **values,
575 for (i = 0; i < nitems; i++)
579 inc = ArrayCastAndSet(values[i], typbyval, typlen, p);
587 /*-------------------------------------------------------------------------
589 * takes the internal representation of an array and returns a string
590 * containing the array in its external format.
591 *-------------------------------------------------------------------------
594 array_out(ArrayType *v, Oid element_type)
622 if (v == (ArrayType *) NULL)
623 return (char *) NULL;
625 if (ARR_IS_LO(v) == true)
631 /* get a wide string to print to */
632 p = array_dims(v, &dummy_bool);
633 nbytes = strlen(ARR_DATA_PTR(v)) + VARHDRSZ + *(int *) p;
635 save_p = (char *) palloc(nbytes);
637 strcpy(save_p, p + sizeof(int));
638 strcat(save_p, ASSGN);
639 strcat(save_p, ARR_DATA_PTR(v));
644 system_cache_lookup(element_type, false, &typlen, &typbyval,
645 &typdelim, &typelem, &typoutput, &typalign);
646 fmgr_info(typoutput, &outputproc);
647 sprintf(delim, "%c", typdelim);
650 nitems = getNitems(ndim, dim);
654 char *emptyArray = palloc(3);
658 emptyArray[2] = '\0';
663 overall_length = 1; /* [TRH] don't forget to count \0 at end. */
664 values = (char **) palloc(nitems * sizeof(char *));
665 for (i = 0; i < nitems; i++)
672 values[i] = (*fmgr_faddr(&outputproc)) (*p, typelem);
675 values[i] = (*fmgr_faddr(&outputproc)) (*(int16 *) p, typelem);
679 values[i] = (*fmgr_faddr(&outputproc)) (*(int32 *) p, typelem);
686 values[i] = (*fmgr_faddr(&outputproc)) (p, typelem);
690 p += INTALIGN(*(int32 *) p);
693 * For the pair of double quotes
697 for (tmp = values[i]; *tmp; tmp++)
709 * count total number of curly braces in output string
711 for (i = j = 0, k = 1; i < ndim; k *= dim[i++], j += k);
713 p = (char *) palloc(overall_length + 2 * j);
717 for (i = 0; i < ndim; indx[i++] = 0);
722 for (i = j; i < ndim - 1; i++)
726 * Surround anything that is not passed by value in double quotes.
727 * See above for more details.
734 for (tmp = values[k]; *tmp; tmp++)
742 strcat(p, values[k]);
747 strcat(p, values[k]);
750 for (i = ndim - 1; i >= 0; i--)
752 indx[i] = (indx[i] + 1) % dim[i];
768 /*-----------------------------------------------------------------------------
770 * returns the dimension of the array pointed to by "v"
771 *----------------------------------------------------------------------------
774 array_dims(ArrayType *v, bool *isNull)
783 if (v == (ArrayType *) NULL)
785 nbytes = ARR_NDIM(v) * 33;
788 * 33 since we assume 15 digits per number + ':' +'[]'
790 save_p = p = (char *) palloc(nbytes + VARHDRSZ);
791 MemSet(save_p, 0, nbytes + VARHDRSZ);
795 for (i = 0; i < ARR_NDIM(v); i++)
797 sprintf(p, "[%d:%d]", lb[i], dimv[i] + lb[i] - 1);
800 nbytes = strlen(save_p + VARHDRSZ) + VARHDRSZ;
801 memmove(save_p, &nbytes, VARHDRSZ);
805 /*---------------------------------------------------------------------------
807 * This routing takes an array pointer and an index array and returns
808 * a pointer to the referred element if element is passed by
809 * reference otherwise returns the value of the referred element.
810 *---------------------------------------------------------------------------
813 array_ref(ArrayType *array,
827 struct varlena *v = NULL;
830 if (array == (ArrayType *) NULL)
836 * fixed length arrays -- these are assumed to be 1-d
838 if (indx[0] * elmlen > arraylen)
839 elog(ERROR, "array_ref: array bound exceeded");
840 retval = (char *) array + indx[0] * elmlen;
841 return _ArrayCast(retval, reftype, elmlen);
843 dim = ARR_DIMS(array);
844 lb = ARR_LBOUND(array);
845 ndim = ARR_NDIM(array);
846 nbytes = (*(int32 *) array) - ARR_OVERHEAD(ndim);
848 if (!SanityCheckInput(ndim, n, dim, lb, indx))
851 offset = GetOffset(n, dim, lb, indx);
853 if (ARR_IS_LO(array))
858 /* We are assuming fixed element lengths here */
860 lo_name = (char *) ARR_DATA_PTR(array);
862 if ((fd = LOopen(lo_name, ARR_IS_INV(array) ? INV_READ : O_RDONLY)) < 0)
865 if (ARR_IS_CHUNKED(array))
866 v = _ReadChunkArray1El(indx, elmlen, fd, array, isNull);
869 if (lo_lseek(fd, offset, SEEK_SET) < 0)
872 v = (struct varlena *) LOread(fd, elmlen);
877 if (VARSIZE(v) - VARHDRSZ < elmlen)
880 retval = (char *) _ArrayCast((char *) VARDATA(v), reftype, elmlen);
883 char *tempdata = palloc(elmlen);
885 memmove(tempdata, retval, elmlen);
889 return (Datum) retval;
894 offset = offset * elmlen;
895 /* off the end of the array */
896 if (nbytes - offset < 1)
898 retval = ARR_DATA_PTR(array) + offset;
899 return _ArrayCast(retval, reftype, elmlen);
907 temp = ARR_DATA_PTR(array);
909 while (bytes > 0 && !done)
916 bytes -= INTALIGN(*(int32 *) temp);
917 temp += INTALIGN(*(int32 *) temp);
922 return (Datum) retval;
926 /*-----------------------------------------------------------------------------
928 * This routine takes an array and a range of indices (upperIndex and
929 * lowerIndx), creates a new array structure for the referred elements
930 * and returns a pointer to it.
931 *-----------------------------------------------------------------------------
934 array_clip(ArrayType *array,
952 if (array == (ArrayType *) NULL)
954 dim = ARR_DIMS(array);
955 lb = ARR_LBOUND(array);
956 ndim = ARR_NDIM(array);
957 nbytes = (*(int32 *) array) - ARR_OVERHEAD(ndim);
959 if (!SanityCheckInput(ndim, n, dim, lb, upperIndx))
962 if (!SanityCheckInput(ndim, n, dim, lb, lowerIndx))
965 for (i = 0; i < n; i++)
966 if (lowerIndx[i] > upperIndx[i])
967 elog(ERROR, "lowerIndex cannot be larger than upperIndx");
968 mda_get_range(n, span, lowerIndx, upperIndx);
970 if (ARR_IS_LO(array))
976 char *newname = NULL;
983 elog(ERROR, "array_clip: array of variable length objects not supported");
985 lo_name = (char *) ARR_DATA_PTR(array);
986 if ((fd = LOopen(lo_name, ARR_IS_INV(array) ? INV_READ : O_RDONLY)) < 0)
988 newname = _array_newLO(&newfd, Unix);
990 bytes = strlen(newname) + 1 + ARR_OVERHEAD(n);
991 newArr = (ArrayType *) palloc(bytes);
992 memmove(newArr, array, sizeof(ArrayType));
993 memmove(newArr, &bytes, sizeof(int));
994 memmove(ARR_DIMS(newArr), span, n * sizeof(int));
995 memmove(ARR_LBOUND(newArr), lowerIndx, n * sizeof(int));
996 strcpy(ARR_DATA_PTR(newArr), newname);
998 rsize = compute_size(lowerIndx, upperIndx, n, len);
999 if (rsize < MAX_BUFF_SIZE)
1004 buff = palloc(rsize);
1007 if (ARR_IS_CHUNKED(array))
1009 _ReadChunkArray(lowerIndx, upperIndx, len, fd, &(buff[VARHDRSZ]),
1014 _ReadArray(lowerIndx, upperIndx, len, fd, (int) &(buff[VARHDRSZ]),
1018 memmove(buff, &rsize, VARHDRSZ);
1021 bytes = LOwrite(newfd, (struct varlena *) buff);
1027 if (ARR_IS_CHUNKED(array))
1029 _ReadChunkArray(lowerIndx, upperIndx, len, fd, (char *) newfd, array,
1033 _ReadArray(lowerIndx, upperIndx, len, fd, newfd, array, 1, isNull);
1045 return (Datum) newArr;
1050 bytes = getNitems(n, span);
1051 bytes = bytes * len + ARR_OVERHEAD(n);
1055 bytes = _ArrayClipCount(lowerIndx, upperIndx, array);
1056 bytes += ARR_OVERHEAD(n);
1058 newArr = (ArrayType *) palloc(bytes);
1059 memmove(newArr, array, sizeof(ArrayType));
1060 memmove(newArr, &bytes, sizeof(int));
1061 memmove(ARR_DIMS(newArr), span, n * sizeof(int));
1062 memmove(ARR_LBOUND(newArr), lowerIndx, n * sizeof(int));
1063 _ArrayRange(lowerIndx, upperIndx, len, ARR_DATA_PTR(newArr), array, 1);
1064 return (Datum) newArr;
1067 /*-----------------------------------------------------------------------------
1069 * This routine sets the value of an array location (specified by an index array)
1070 * to a new value specified by "dataPtr".
1072 * returns a pointer to the modified array.
1073 *-----------------------------------------------------------------------------
1076 array_set(ArrayType *array,
1092 if (array == (ArrayType *) NULL)
1098 * fixed length arrays -- these are assumed to be 1-d
1100 if (indx[0] * elmlen > arraylen)
1101 elog(ERROR, "array_ref: array bound exceeded");
1102 pos = (char *) array + indx[0] * elmlen;
1103 ArrayCastAndSet(dataPtr, (bool) reftype, elmlen, pos);
1104 return (char *) array;
1106 dim = ARR_DIMS(array);
1107 lb = ARR_LBOUND(array);
1108 ndim = ARR_NDIM(array);
1109 nbytes = (*(int32 *) array) - ARR_OVERHEAD(ndim);
1111 if (!SanityCheckInput(ndim, n, dim, lb, indx))
1113 elog(ERROR, "array_set: array bound exceeded");
1114 return (char *) array;
1116 offset = GetOffset(n, dim, lb, indx);
1118 if (ARR_IS_LO(array))
1123 /* We are assuming fixed element lengths here */
1128 lo_name = ARR_DATA_PTR(array);
1129 if ((fd = LOopen(lo_name, ARR_IS_INV(array) ? INV_WRITE : O_WRONLY)) < 0)
1130 return (char *) array;
1132 if (lo_lseek(fd, offset, SEEK_SET) < 0)
1133 return (char *) array;
1134 v = (struct varlena *) palloc(elmlen + VARHDRSZ);
1135 VARSIZE(v) = elmlen + VARHDRSZ;
1136 ArrayCastAndSet(dataPtr, (bool) reftype, elmlen, VARDATA(v));
1142 * if (n < VARSIZE(v) - VARHDRSZ) RETURN_NULL;
1146 return (char *) array;
1150 offset = offset * elmlen;
1151 /* off the end of the array */
1152 if (nbytes - offset < 1)
1153 return (char *) array;
1154 pos = ARR_DATA_PTR(array) + offset;
1158 ArrayType *newarray;
1168 elt_ptr = array_seek(ARR_DATA_PTR(array), -1, offset);
1169 oldlen = INTALIGN(*(int32 *) elt_ptr);
1170 newlen = INTALIGN(*(int32 *) dataPtr);
1172 if (oldlen == newlen)
1174 /* new element with same size, overwrite old data */
1175 ArrayCastAndSet(dataPtr, (bool) reftype, elmlen, elt_ptr);
1176 return (char *) array;
1179 /* new element with different size, reallocate the array */
1180 oldsize = array->size;
1181 lth0 = ARR_OVERHEAD(n);
1182 lth1 = (int) (elt_ptr - ARR_DATA_PTR(array));
1183 lth2 = (int) (oldsize - lth0 - lth1 - oldlen);
1184 newsize = lth0 + lth1 + newlen + lth2;
1186 newarray = (ArrayType *) palloc(newsize);
1187 memmove((char *) newarray, (char *) array, lth0 + lth1);
1188 newarray->size = newsize;
1189 newlen = ArrayCastAndSet(dataPtr, (bool) reftype, elmlen,
1190 (char *) newarray + lth0 + lth1);
1191 memmove((char *) newarray + lth0 + lth1 + newlen,
1192 (char *) array + lth0 + lth1 + oldlen, lth2);
1194 /* ??? who should free this storage ??? */
1195 return (char *) newarray;
1197 ArrayCastAndSet(dataPtr, (bool) reftype, elmlen, pos);
1198 return (char *) array;
1201 /*----------------------------------------------------------------------------
1203 * This routine sets the value of a range of array locations (specified
1204 * by upper and lower index values ) to new values passed as
1207 * returns a pointer to the modified array.
1208 *----------------------------------------------------------------------------
1211 array_assgn(ArrayType *array,
1225 if (array == (ArrayType *) NULL)
1228 elog(ERROR, "array_assgn:updates on arrays of variable length elements not allowed");
1230 dim = ARR_DIMS(array);
1231 lb = ARR_LBOUND(array);
1232 ndim = ARR_NDIM(array);
1234 if (!SanityCheckInput(ndim, n, dim, lb, upperIndx) ||
1235 !SanityCheckInput(ndim, n, dim, lb, lowerIndx))
1236 return (char *) array;
1238 for (i = 0; i < n; i++)
1239 if (lowerIndx[i] > upperIndx[i])
1240 elog(ERROR, "lowerIndex larger than upperIndx");
1242 if (ARR_IS_LO(array))
1250 lo_name = (char *) ARR_DATA_PTR(array);
1251 if ((fd = LOopen(lo_name, ARR_IS_INV(array) ? INV_WRITE : O_WRONLY)) < 0)
1252 return (char *) array;
1254 if (ARR_IS_LO(newArr))
1257 lo_name = (char *) ARR_DATA_PTR(newArr);
1258 if ((newfd = LOopen(lo_name, ARR_IS_INV(newArr) ? INV_READ : O_RDONLY)) < 0)
1259 return (char *) array;
1261 _LOArrayRange(lowerIndx, upperIndx, len, fd, newfd, array, 1, isNull);
1266 _LOArrayRange(lowerIndx, upperIndx, len, fd, (int) ARR_DATA_PTR(newArr),
1270 return (char *) array;
1272 _ArrayRange(lowerIndx, upperIndx, len, ARR_DATA_PTR(newArr), array, 0);
1273 return (char *) array;
1279 * Map an arbitrary function to an array and return a new array with
1280 * same dimensions and the source elements transformed by fn().
1283 array_map(ArrayType *v,
1311 /* Large objects not yet supported */
1312 if (ARR_IS_LO(v) == true)
1313 elog(ERROR, "array_map: large objects not supported");
1316 if ((nargs < 0) || (nargs > 4))
1317 elog(ERROR, "array_map: invalid nargs: %d", nargs);
1319 /* Copy extra args to local variable */
1320 va_start(ap, nargs);
1321 for (i = 0; i < nargs; i++)
1322 args[i] = (void *) va_arg(ap, char *);
1325 /* Lookup source and result types. Unneeded variables are reused. */
1326 system_cache_lookup(type, false, &inp_typlen, &inp_typbyval,
1327 &typdelim, &typelem, &proc, &typalign);
1328 system_cache_lookup(retType, false, &typlen, &typbyval,
1329 &typdelim, &typelem, &proc, &typalign);
1333 nitems = getNitems(ndim, dim);
1335 /* Check for empty array */
1339 /* Allocate temporary array for new values */
1340 values = (char **) palloc(nitems * sizeof(char *));
1341 MemSet(values, 0, nitems * sizeof(char *));
1343 /* Loop over source data */
1344 s = (char *) ARR_DATA_PTR(v);
1345 for (i = 0; i < nitems; i++)
1347 /* Get source element */
1353 elt = (char *) ((int) (*(char *) s));
1356 elt = (char *) ((int) (*(int16 *) s));
1361 elt = (char *) (*(int32 *) s);
1372 s += INTALIGN(*(int32 *) s);
1376 * Apply the given function to source elt and extra args. nargs is
1377 * the number of extra args taken by fn().
1382 p = (char *) (*fn) (elt);
1385 p = (char *) (*fn) (elt, args[0]);
1388 p = (char *) (*fn) (elt, args[0], args[1]);
1391 p = (char *) (*fn) (elt, args[0], args[1], args[2]);
1395 p = (char *) (*fn) (elt, args[0], args[1], args[2], args[3]);
1399 /* Update values and total result size */
1402 values[i] = (char *) p;
1409 len = ((typlen > 0) ? typlen : INTALIGN(*(int32 *) p));
1410 /* Needed because _CopyArrayEls tries to pfree items */
1413 p = (char *) palloc(len);
1414 memcpy(p, elt, len);
1416 values[i] = (char *) p;
1421 /* Allocate and initialize the result array */
1422 nbytes += ARR_OVERHEAD(ndim);
1423 result = (ArrayType *) palloc(nbytes);
1424 MemSet(result, 0, nbytes);
1426 memcpy((char *) result, (char *) &nbytes, sizeof(int));
1427 memcpy((char *) ARR_NDIM_PTR(result), (char *) &ndim, sizeof(int));
1428 memcpy((char *) ARR_DIMS(result), ARR_DIMS(v), 2 * ndim * sizeof(int));
1430 /* Copy new values into the result array. values is pfreed. */
1431 _CopyArrayEls((char **) values,
1432 ARR_DATA_PTR(result), nitems,
1433 typlen, typalign, typbyval);
1438 /*-----------------------------------------------------------------------------
1440 * compares two arrays for equality
1442 * returns 1 if the arrays are equal, 0 otherwise.
1443 *-----------------------------------------------------------------------------
1446 array_eq(ArrayType *array1, ArrayType *array2)
1448 if ((array1 == NULL) || (array2 == NULL))
1450 if (*(int *) array1 != *(int *) array2)
1452 if (memcmp(array1, array2, *(int *) array1))
1457 /***************************************************************************/
1458 /******************| Support Routines |*****************/
1459 /***************************************************************************/
1461 system_cache_lookup(Oid element_type,
1470 HeapTuple typeTuple;
1471 Form_pg_type typeStruct;
1473 typeTuple = SearchSysCacheTuple(TYPOID,
1474 ObjectIdGetDatum(element_type),
1477 if (!HeapTupleIsValid(typeTuple))
1479 elog(ERROR, "array_out: Cache lookup failed for type %u\n",
1483 typeStruct = (Form_pg_type) GETSTRUCT(typeTuple);
1484 *typlen = typeStruct->typlen;
1485 *typbyval = typeStruct->typbyval;
1486 *typdelim = typeStruct->typdelim;
1487 *typelem = typeStruct->typelem;
1488 *typalign = typeStruct->typalign;
1490 *proc = typeStruct->typinput;
1492 *proc = typeStruct->typoutput;
1496 _ArrayCast(char *value, bool byval, int len)
1503 return (Datum) *value;
1505 return (Datum) *(int16 *) value;
1508 return (Datum) *(int32 *) value;
1510 elog(ERROR, "array_ref: byval and elt len > 4!");
1515 return (Datum) value;
1521 ArrayCastAndSet(char *src,
1535 *dest = DatumGetChar(src);
1538 *(int16 *) dest = DatumGetInt16(src);
1541 *(int32 *) dest = (int32) src;
1546 memmove(dest, src, typlen);
1551 memmove(dest, src, *(int32 *) src);
1552 inc = (INTALIGN(*(int32 *) src));
1559 _AdvanceBy1word(char *str, char **word)
1567 while (isspace(*str))
1570 if ((space = (char *) strchr(str, ' ')) != (char *) NULL)
1583 SanityCheckInput(int ndim, int n, int *dim, int *lb, int *indx)
1587 /* Do Sanity check on input */
1590 for (i = 0; i < ndim; i++)
1591 if ((lb[i] > indx[i]) || (indx[i] >= (dim[i] + lb[i])))
1597 _ArrayRange(int *st,
1617 n = ARR_NDIM(array);
1618 dim = ARR_DIMS(array);
1619 lb = ARR_LBOUND(array);
1620 srcPtr = ARR_DATA_PTR(array);
1621 for (i = 0; i < n; st[i] -= lb[i], endp[i] -= lb[i], i++);
1622 mda_get_prod(n, dim, prod);
1623 st_pos = tuple2linear(n, st, prod);
1624 srcPtr = array_seek(srcPtr, bsize, st_pos);
1625 mda_get_range(n, span, st, endp);
1626 mda_get_offset_values(n, dist, prod, span);
1627 for (i = 0; i < n; indx[i++] = 0);
1632 srcPtr = array_seek(srcPtr, bsize, dist[j]);
1634 inc = array_read(destPtr, bsize, 1, srcPtr);
1636 inc = array_read(srcPtr, bsize, 1, destPtr);
1639 } while ((j = next_tuple(i + 1, indx, span)) != -1);
1643 _ArrayClipCount(int *stI, int *endpI, ArrayType *array)
1661 n = ARR_NDIM(array);
1662 dim = ARR_DIMS(array);
1663 lb = ARR_LBOUND(array);
1664 ptr = ARR_DATA_PTR(array);
1665 for (i = 0; i < n; st[i] = stI[i] - lb[i], endp[i] = endpI[i] - lb[i], i++);
1666 mda_get_prod(n, dim, prod);
1667 st_pos = tuple2linear(n, st, prod);
1668 ptr = array_seek(ptr, -1, st_pos);
1669 mda_get_range(n, span, st, endp);
1670 mda_get_offset_values(n, dist, prod, span);
1671 for (i = 0; i < n; indx[i++] = 0);
1675 ptr = array_seek(ptr, -1, dist[j]);
1676 inc = INTALIGN(*(int32 *) ptr);
1679 } while ((j = next_tuple(i + 1, indx, span)) != -1);
1684 array_seek(char *ptr, int eltsize, int nitems)
1689 return ptr + eltsize * nitems;
1690 for (i = 0; i < nitems; i++)
1691 ptr += INTALIGN(*(int32 *) ptr);
1696 array_read(char *destptr, int eltsize, int nitems, char *srcptr)
1704 memmove(destptr, srcptr, eltsize * nitems);
1705 return eltsize * nitems;
1707 for (i = inc = 0; i < nitems; i++)
1709 tmp = (INTALIGN(*(int32 *) srcptr));
1710 memmove(destptr, srcptr, tmp);
1719 _LOArrayRange(int *st,
1742 n = ARR_NDIM(array);
1743 dim = ARR_DIMS(array);
1744 lb = ARR_LBOUND(array);
1745 for (i = 0; i < n; st[i] -= lb[i], endp[i] -= lb[i], i++);
1747 mda_get_prod(n, dim, prod);
1748 st_pos = tuple2linear(n, st, prod);
1749 offset = st_pos * bsize;
1750 if (lo_lseek(srcfd, offset, SEEK_SET) < 0)
1752 mda_get_range(n, span, st, endp);
1753 mda_get_offset_values(n, dist, prod, span);
1754 for (i = 0; i < n; indx[i++] = 0);
1755 for (i = n - 1, inc = bsize; i >= 0; inc *= span[i--])
1761 offset += (dist[j] * bsize);
1762 if (lo_lseek(srcfd, offset, SEEK_SET) < 0)
1764 tmp = _LOtransfer((char **) &srcfd, inc, 1, (char **) &destfd, isSrcLO, 1);
1768 } while ((j = next_tuple(i + 1, indx, span)) != -1);
1796 n = ARR_NDIM(array);
1797 dim = ARR_DIMS(array);
1798 lb = ARR_LBOUND(array);
1799 for (i = 0; i < n; st[i] -= lb[i], endp[i] -= lb[i], i++);
1801 mda_get_prod(n, dim, prod);
1802 st_pos = tuple2linear(n, st, prod);
1803 offset = st_pos * bsize;
1804 if (lo_lseek(srcfd, offset, SEEK_SET) < 0)
1806 mda_get_range(n, span, st, endp);
1807 mda_get_offset_values(n, dist, prod, span);
1808 for (i = 0; i < n; indx[i++] = 0);
1809 for (i = n - 1, inc = bsize; i >= 0; inc *= span[i--])
1815 offset += (dist[j] * bsize);
1816 if (lo_lseek(srcfd, offset, SEEK_SET) < 0)
1818 tmp = _LOtransfer((char **) &destfd, inc, 1, (char **) &srcfd, 1, isDestLO);
1822 } while ((j = next_tuple(i + 1, indx, span)) != -1);
1827 _LOtransfer(char **destfd,
1834 #define MAX_READ (512 * 1024)
1835 #define min(a, b) (a < b ? a : b)
1836 struct varlena *v = NULL;
1841 inc = nitems * size;
1842 if (isSrcLO && isDestLO && inc > 0)
1843 for (tmp = 0, resid = inc;
1844 resid > 0 && (inc = min(resid, MAX_READ)) > 0; resid -= inc)
1847 v = (struct varlena *) LOread((int) *srcfd, inc);
1848 if (VARSIZE(v) - VARHDRSZ < inc)
1853 tmp += LOwrite((int) *destfd, v);
1858 else if (!isSrcLO && isDestLO)
1860 tmp = lo_write((int) *destfd, *srcfd, inc);
1861 *srcfd = *srcfd + tmp;
1863 else if (isSrcLO && !isDestLO)
1865 tmp = lo_read((int) *srcfd, *destfd, inc);
1866 *destfd = *destfd + tmp;
1870 memmove(*destfd, *srcfd, inc);
1880 _array_newLO(int *fd, int flag)
1883 char saveName[NAME_LEN];
1885 p = (char *) palloc(NAME_LEN);
1886 sprintf(p, "/Arry.%u", newoid());
1887 strcpy(saveName, p);
1889 if ((*fd = LOcreat(saveName, 0600, flag)) < 0)
1890 elog(ERROR, "Large object create failed");