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.44 1999/07/15 15:20:07 momjian Exp $
12 *-------------------------------------------------------------------------
22 #include "catalog/catalog.h"
23 #include "catalog/pg_type.h"
25 #include "utils/syscache.h"
26 #include "utils/memutils.h"
27 #include "storage/fd.h"
29 #include "utils/array.h"
31 #include "libpq/libpq-fs.h"
32 #include "libpq/be-fsstubs.h"
36 /* An array has the following internal structure:
37 * <nbytes> - total number of bytes
38 * <ndim> - number of dimensions of the array
39 * <flags> - bit mask of flags
40 * <dim> - size of each array axis
41 * <dim_lower> - lower boundary of each dimension
42 * <actual data> - whatever is the stored data
45 /*-=-=--=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-*/
46 static int _ArrayCount(char *str, int *dim, int typdelim);
47 static char *_ReadArrayStr(char *arrayStr, int nitems, int ndim, int *dim,
48 FmgrInfo *inputproc, Oid typelem, int32 typmod,
49 char typdelim, int typlen, bool typbyval,
50 char typalign, int *nbytes);
53 static char *_ReadLOArray(char *str, int *nbytes, int *fd, bool *chunkFlag,
54 int ndim, int *dim, int baseSize);
57 static void _CopyArrayEls(char **values, char *p, int nitems, int typlen,
58 char typalign, bool typbyval);
59 static void system_cache_lookup(Oid element_type, bool input, int *typlen,
60 bool *typbyval, char *typdelim, Oid *typelem, Oid *proc,
62 static Datum _ArrayCast(char *value, bool byval, int len);
65 static char *_AdvanceBy1word(char *str, char **word);
68 static void _ArrayRange(int *st, int *endp, int bsize, char *destPtr,
69 ArrayType *array, int from);
70 static int _ArrayClipCount(int *stI, int *endpI, ArrayType *array);
71 static void _LOArrayRange(int *st, int *endp, int bsize, int srcfd,
72 int destfd, ArrayType *array, int isSrcLO, bool *isNull);
73 static void _ReadArray(int *st, int *endp, int bsize, int srcfd, int destfd,
74 ArrayType *array, int isDestLO, bool *isNull);
75 static int ArrayCastAndSet(char *src, bool typbyval, int typlen, char *dest);
76 static int SanityCheckInput(int ndim, int n, int *dim, int *lb, int *indx);
77 static int array_read(char *destptr, int eltsize, int nitems, char *srcptr);
78 static char *array_seek(char *ptr, int eltsize, int nitems);
80 /*---------------------------------------------------------------------
82 * converts an array from the external format in "string" to
85 * the internal representation of the input array
86 *--------------------------------------------------------------------
89 array_in(char *string, /* input array in external form */
90 Oid element_type, /* type OID of an array element */
108 ArrayType *retval = NULL;
114 system_cache_lookup(element_type, true, &typlen, &typbyval, &typdelim,
115 &typelem, &typinput, &typalign);
117 fmgr_info(typinput, &inputproc);
119 string_save = (char *) palloc(strlen(string) + 3);
120 strcpy(string_save, string);
122 /* --- read array dimensions ---------- */
125 for (ndim = 0; !done;)
132 if ((r = (char *) strchr(p, ':')) == (char *) NULL)
137 lBound[ndim] = atoi(p);
140 for (q = p; isdigit(*q); q++);
142 elog(ERROR, "array_in: missing ']' in array declaration");
145 if ((dim[ndim] < 0) || (lBound[ndim] < 0))
146 elog(ERROR, "array_in: array dimensions need to be positive");
147 dim[ndim] = dim[ndim] - lBound[ndim] + 1;
149 elog(ERROR, "array_in: upper_bound cannot be < lower_bound");
161 ndim = _ArrayCount(p, dim, typdelim);
162 for (i = 0; i < ndim; lBound[i++] = 1);
165 elog(ERROR, "array_in: Need to specify dimension");
171 if (strncmp(p, ASSGN, strlen(ASSGN)))
172 elog(ERROR, "array_in: missing assignment operator");
179 printf("array_in- ndim %d (", ndim);
180 for (i = 0; i < ndim; i++)
182 printf(" %d", dim[i]);
184 printf(") for %s\n", string);
187 nitems = getNitems(ndim, dim);
190 char *emptyArray = palloc(sizeof(ArrayType));
192 MemSet(emptyArray, 0, sizeof(ArrayType));
193 *(int32 *) emptyArray = sizeof(ArrayType);
199 /* array not a large object */
200 dataPtr = (char *) _ReadArrayStr(p, nitems, ndim, dim, &inputproc, typelem,
201 typmod, typdelim, typlen, typbyval, typalign,
203 nbytes += ARR_OVERHEAD(ndim);
204 retval = (ArrayType *) palloc(nbytes);
205 MemSet(retval, 0, nbytes);
206 memmove(retval, (char *) &nbytes, sizeof(int));
207 memmove((char *) ARR_NDIM_PTR(retval), (char *) &ndim, sizeof(int));
208 SET_LO_FLAG(false, retval);
209 memmove((char *) ARR_DIMS(retval), (char *) dim, ndim * sizeof(int));
210 memmove((char *) ARR_LBOUND(retval), (char *) lBound,
214 * dataPtr is an array of arbitraystuff even though its type is
215 * char* cast to char** to pass to _CopyArrayEls for now - jolly
217 _CopyArrayEls((char **) dataPtr,
218 ARR_DATA_PTR(retval), nitems,
219 typlen, typalign, typbyval);
226 bool chunked = false;
228 dataPtr = _ReadLOArray(p, &bytes, &dummy, &chunked, ndim,
230 nbytes = bytes + ARR_OVERHEAD(ndim);
231 retval = (ArrayType *) palloc(nbytes);
232 MemSet(retval, 0, nbytes);
233 memmove(retval, (char *) &nbytes, sizeof(int));
234 memmove((char *) ARR_NDIM_PTR(retval), (char *) &ndim, sizeof(int));
235 SET_LO_FLAG(true, retval);
236 SET_CHUNK_FLAG(chunked, retval);
237 memmove((char *) ARR_DIMS(retval), (char *) dim, ndim * sizeof(int));
238 memmove((char *) ARR_LBOUND(retval), (char *) lBound, ndim * sizeof(int));
239 memmove(ARR_DATA_PTR(retval), dataPtr, bytes);
241 elog(ERROR, "large object arrays not supported");
244 return (char *) retval;
247 /*-----------------------------------------------------------------------------
249 * Counts the number of dimensions and the *dim array for an array string.
250 * The syntax for array input is C-like nested curly braces
251 *-----------------------------------------------------------------------------
254 _ArrayCount(char *str, int *dim, int typdelim)
260 bool scanning_string = false;
261 bool eoArray = false;
264 for (i = 0; i < MAXDIM; ++i)
265 temp[i] = dim[i] = 0;
267 if (strncmp(str, "{}", 2) == 0)
271 while (eoArray != true)
280 /* skip escaped characters (\ and ") inside strings */
281 if (scanning_string && *(q + 1))
287 * Signal a premature end of the string. DZ -
290 elog(ERROR, "malformed array constant: %s", str);
293 scanning_string = !scanning_string;
296 if (!scanning_string)
298 temp[nest_level] = 0;
303 if (!scanning_string)
309 temp[nest_level - 1]++;
311 eoArray = done = true;
317 if (*q == typdelim && !scanning_string)
330 for (i = 0; i < ndim; ++i)
336 /*---------------------------------------------------------------------------
338 * parses the array string pointed by "arrayStr" and converts it in the
339 * internal format. The external format expected is like C array
340 * declaration. Unspecified elements are initialized to zero for fixed length
341 * base types and to empty varlena structures for variable length base
344 * returns the internal representation of the array elements
345 * nbytes is set to the size of the array in its internal representation.
346 *---------------------------------------------------------------------------
349 _ReadArrayStr(char *arrayStr,
353 FmgrInfo *inputproc, /* function used for the
369 bool scanning_string = false;
372 bool eoArray = false;
374 mda_get_prod(ndim, dim, prod);
375 for (i = 0; i < ndim; indx[i++] = 0);
376 /* read array enclosed within {} */
377 values = (char **) palloc(nitems * sizeof(char *));
378 MemSet(values, 0, nitems * sizeof(char *));
391 /* Crunch the string on top of the backslash. */
392 for (r = q; *r != '\0'; r++)
396 if (!scanning_string)
400 p++; /* get p past first doublequote */
404 scanning_string = !scanning_string;
407 if (!scanning_string)
411 if (nest_level > ndim)
412 elog(ERROR, "array_in: illformed array constant");
413 indx[nest_level - 1] = 0;
418 if (!scanning_string)
421 i = tuple2linear(ndim, indx, prod);
424 eoArray = done = true;
428 indx[nest_level - 1]++;
433 if (*q == typdelim && !scanning_string)
436 i = tuple2linear(ndim, indx, prod);
447 elog(ERROR, "array_in: illformed array constant");
448 values[i] = (*fmgr_faddr(inputproc)) (p, typelem, typmod);
453 * if not at the end of the array skip white space
463 *nbytes = nitems * typlen;
465 for (i = 0; i < nitems; i++)
468 values[i] = palloc(typlen);
469 MemSet(values[i], 0, typlen);
474 for (i = 0, *nbytes = 0; i < nitems; i++)
479 *nbytes += DOUBLEALIGN(*(int32 *) values[i]);
481 *nbytes += INTALIGN(*(int32 *) values[i]);
485 *nbytes += sizeof(int32);
486 values[i] = palloc(sizeof(int32));
487 *(int32 *) values[i] = sizeof(int32);
491 return (char *) values;
495 /*----------------------------------------------------------------------------
496 * Read data about an array to be stored as a large object
497 *----------------------------------------------------------------------------
501 _ReadLOArray(char *str,
516 str = _AdvanceBy1word(str, &inputfile);
522 str = _AdvanceBy1word(str, &word);
524 if (!strcmp(word, "-chunk"))
527 elog(ERROR, "array_in: access pattern file required");
528 str = _AdvanceBy1word(str, &accessfile);
530 else if (!strcmp(word, "-noreorg"))
533 elog(ERROR, "array_in: chunk file required");
534 str = _AdvanceBy1word(str, &chunkfile);
537 elog(ERROR, "usage: <input file> -chunk DEFAULT/<access pattern file> -invert/-native [-noreorg <chunk file>]");
540 if (inputfile == NULL)
541 elog(ERROR, "array_in: missing file name");
542 lobjId = lo_creat(0);
543 *fd = lo_open(lobjId, INV_READ);
545 elog(ERROR, "Large object create failed");
547 *nbytes = strlen(retStr) + 2;
554 if ((afd = AllocateFile(accessfile, "r")) == NULL)
556 if ((afd = AllocateFile(accessfile, "r")) == NULL)
558 elog(ERROR, "unable to open access pattern file");
560 retStr = _ChunkArray(*fd, afd, ndim, dim, baseSize, nbytes,
570 _CopyArrayEls(char **values,
579 for (i = 0; i < nitems; i++)
583 inc = ArrayCastAndSet(values[i], typbyval, typlen, p);
591 /*-------------------------------------------------------------------------
593 * takes the internal representation of an array and returns a string
594 * containing the array in its external format.
595 *-------------------------------------------------------------------------
598 array_out(ArrayType *v, Oid element_type)
626 if (v == (ArrayType *) NULL)
627 return (char *) NULL;
629 if (ARR_IS_LO(v) == true)
635 /* get a wide string to print to */
636 p = array_dims(v, &dummy_bool);
637 nbytes = strlen(ARR_DATA_PTR(v)) + VARHDRSZ + *(int *) p;
639 save_p = (char *) palloc(nbytes);
641 strcpy(save_p, p + sizeof(int));
642 strcat(save_p, ASSGN);
643 strcat(save_p, ARR_DATA_PTR(v));
648 system_cache_lookup(element_type, false, &typlen, &typbyval,
649 &typdelim, &typelem, &typoutput, &typalign);
650 fmgr_info(typoutput, &outputproc);
651 sprintf(delim, "%c", typdelim);
654 nitems = getNitems(ndim, dim);
658 char *emptyArray = palloc(3);
662 emptyArray[2] = '\0';
667 overall_length = 1; /* [TRH] don't forget to count \0 at end. */
668 values = (char **) palloc(nitems * sizeof(char *));
669 for (i = 0; i < nitems; i++)
676 values[i] = (*fmgr_faddr(&outputproc)) (*p, typelem);
679 values[i] = (*fmgr_faddr(&outputproc)) (*(int16 *) p, typelem);
683 values[i] = (*fmgr_faddr(&outputproc)) (*(int32 *) p, typelem);
690 values[i] = (*fmgr_faddr(&outputproc)) (p, typelem);
694 p += INTALIGN(*(int32 *) p);
697 * For the pair of double quotes
701 for (tmp = values[i]; *tmp; tmp++)
713 * count total number of curly braces in output string
715 for (i = j = 0, k = 1; i < ndim; k *= dim[i++], j += k);
717 p = (char *) palloc(overall_length + 2 * j);
721 for (i = 0; i < ndim; indx[i++] = 0);
726 for (i = j; i < ndim - 1; i++)
730 * Surround anything that is not passed by value in double quotes.
731 * See above for more details.
738 for (tmp = values[k]; *tmp; tmp++)
746 strcat(p, values[k]);
751 strcat(p, values[k]);
754 for (i = ndim - 1; i >= 0; i--)
756 indx[i] = (indx[i] + 1) % dim[i];
772 /*-----------------------------------------------------------------------------
774 * returns the dimension of the array pointed to by "v"
775 *----------------------------------------------------------------------------
778 array_dims(ArrayType *v, bool *isNull)
787 if (v == (ArrayType *) NULL)
789 nbytes = ARR_NDIM(v) * 33;
792 * 33 since we assume 15 digits per number + ':' +'[]'
794 save_p = p = (char *) palloc(nbytes + VARHDRSZ);
795 MemSet(save_p, 0, nbytes + VARHDRSZ);
799 for (i = 0; i < ARR_NDIM(v); i++)
801 sprintf(p, "[%d:%d]", lb[i], dimv[i] + lb[i] - 1);
804 nbytes = strlen(save_p + VARHDRSZ) + VARHDRSZ;
805 memmove(save_p, &nbytes, VARHDRSZ);
809 /*---------------------------------------------------------------------------
811 * This routing takes an array pointer and an index array and returns
812 * a pointer to the referred element if element is passed by
813 * reference otherwise returns the value of the referred element.
814 *---------------------------------------------------------------------------
817 array_ref(ArrayType *array,
831 struct varlena *v = NULL;
834 if (array == (ArrayType *) NULL)
840 * fixed length arrays -- these are assumed to be 1-d
842 if (indx[0] * elmlen > arraylen)
843 elog(ERROR, "array_ref: array bound exceeded");
844 retval = (char *) array + indx[0] * elmlen;
845 return _ArrayCast(retval, reftype, elmlen);
847 dim = ARR_DIMS(array);
848 lb = ARR_LBOUND(array);
849 ndim = ARR_NDIM(array);
850 nbytes = (*(int32 *) array) - ARR_OVERHEAD(ndim);
852 if (!SanityCheckInput(ndim, n, dim, lb, indx))
855 offset = GetOffset(n, dim, lb, indx);
857 if (ARR_IS_LO(array))
862 /* We are assuming fixed element lengths here */
864 lo_name = (char *) ARR_DATA_PTR(array);
866 if ((fd = LOopen(lo_name, ARR_IS_INV(array) ? INV_READ : O_RDONLY)) < 0)
869 if (ARR_IS_CHUNKED(array))
870 v = _ReadChunkArray1El(indx, elmlen, fd, array, isNull);
873 if (lo_lseek(fd, offset, SEEK_SET) < 0)
876 v = (struct varlena *) LOread(fd, elmlen);
881 if (VARSIZE(v) - VARHDRSZ < elmlen)
884 retval = (char *) _ArrayCast((char *) VARDATA(v), reftype, elmlen);
887 char *tempdata = palloc(elmlen);
889 memmove(tempdata, retval, elmlen);
893 return (Datum) retval;
898 offset = offset * elmlen;
899 /* off the end of the array */
900 if (nbytes - offset < 1)
902 retval = ARR_DATA_PTR(array) + offset;
903 return _ArrayCast(retval, reftype, elmlen);
911 temp = ARR_DATA_PTR(array);
913 while (bytes > 0 && !done)
920 bytes -= INTALIGN(*(int32 *) temp);
921 temp += INTALIGN(*(int32 *) temp);
926 return (Datum) retval;
930 /*-----------------------------------------------------------------------------
932 * This routine takes an array and a range of indices (upperIndex and
933 * lowerIndx), creates a new array structure for the referred elements
934 * and returns a pointer to it.
935 *-----------------------------------------------------------------------------
938 array_clip(ArrayType *array,
956 if (array == (ArrayType *) NULL)
958 dim = ARR_DIMS(array);
959 lb = ARR_LBOUND(array);
960 ndim = ARR_NDIM(array);
961 nbytes = (*(int32 *) array) - ARR_OVERHEAD(ndim);
963 if (!SanityCheckInput(ndim, n, dim, lb, upperIndx))
966 if (!SanityCheckInput(ndim, n, dim, lb, lowerIndx))
969 for (i = 0; i < n; i++)
970 if (lowerIndx[i] > upperIndx[i])
971 elog(ERROR, "lowerIndex cannot be larger than upperIndx");
972 mda_get_range(n, span, lowerIndx, upperIndx);
974 if (ARR_IS_LO(array))
980 char *newname = NULL;
987 elog(ERROR, "array_clip: array of variable length objects not supported");
989 lo_name = (char *) ARR_DATA_PTR(array);
990 if ((fd = LOopen(lo_name, ARR_IS_INV(array) ? INV_READ : O_RDONLY)) < 0)
992 newname = _array_newLO(&newfd, Unix);
994 bytes = strlen(newname) + 1 + ARR_OVERHEAD(n);
995 newArr = (ArrayType *) palloc(bytes);
996 memmove(newArr, array, sizeof(ArrayType));
997 memmove(newArr, &bytes, sizeof(int));
998 memmove(ARR_DIMS(newArr), span, n * sizeof(int));
999 memmove(ARR_LBOUND(newArr), lowerIndx, n * sizeof(int));
1000 strcpy(ARR_DATA_PTR(newArr), newname);
1002 rsize = compute_size(lowerIndx, upperIndx, n, len);
1003 if (rsize < MAX_BUFF_SIZE)
1008 buff = palloc(rsize);
1011 if (ARR_IS_CHUNKED(array))
1013 _ReadChunkArray(lowerIndx, upperIndx, len, fd, &(buff[VARHDRSZ]),
1018 _ReadArray(lowerIndx, upperIndx, len, fd, (int) &(buff[VARHDRSZ]),
1022 memmove(buff, &rsize, VARHDRSZ);
1025 bytes = LOwrite(newfd, (struct varlena *) buff);
1031 if (ARR_IS_CHUNKED(array))
1033 _ReadChunkArray(lowerIndx, upperIndx, len, fd, (char *) newfd, array,
1037 _ReadArray(lowerIndx, upperIndx, len, fd, newfd, array, 1, isNull);
1049 return (Datum) newArr;
1054 bytes = getNitems(n, span);
1055 bytes = bytes * len + ARR_OVERHEAD(n);
1059 bytes = _ArrayClipCount(lowerIndx, upperIndx, array);
1060 bytes += ARR_OVERHEAD(n);
1062 newArr = (ArrayType *) palloc(bytes);
1063 memmove(newArr, array, sizeof(ArrayType));
1064 memmove(newArr, &bytes, sizeof(int));
1065 memmove(ARR_DIMS(newArr), span, n * sizeof(int));
1066 memmove(ARR_LBOUND(newArr), lowerIndx, n * sizeof(int));
1067 _ArrayRange(lowerIndx, upperIndx, len, ARR_DATA_PTR(newArr), array, 1);
1068 return (Datum) newArr;
1071 /*-----------------------------------------------------------------------------
1073 * This routine sets the value of an array location (specified by an index array)
1074 * to a new value specified by "dataPtr".
1076 * returns a pointer to the modified array.
1077 *-----------------------------------------------------------------------------
1080 array_set(ArrayType *array,
1096 if (array == (ArrayType *) NULL)
1102 * fixed length arrays -- these are assumed to be 1-d
1104 if (indx[0] * elmlen > arraylen)
1105 elog(ERROR, "array_ref: array bound exceeded");
1106 pos = (char *) array + indx[0] * elmlen;
1107 ArrayCastAndSet(dataPtr, (bool) reftype, elmlen, pos);
1108 return (char *) array;
1110 dim = ARR_DIMS(array);
1111 lb = ARR_LBOUND(array);
1112 ndim = ARR_NDIM(array);
1113 nbytes = (*(int32 *) array) - ARR_OVERHEAD(ndim);
1115 if (!SanityCheckInput(ndim, n, dim, lb, indx))
1117 elog(ERROR, "array_set: array bound exceeded");
1118 return (char *) array;
1120 offset = GetOffset(n, dim, lb, indx);
1122 if (ARR_IS_LO(array))
1127 /* We are assuming fixed element lengths here */
1132 lo_name = ARR_DATA_PTR(array);
1133 if ((fd = LOopen(lo_name, ARR_IS_INV(array) ? INV_WRITE : O_WRONLY)) < 0)
1134 return (char *) array;
1136 if (lo_lseek(fd, offset, SEEK_SET) < 0)
1137 return (char *) array;
1138 v = (struct varlena *) palloc(elmlen + VARHDRSZ);
1139 VARSIZE(v) = elmlen + VARHDRSZ;
1140 ArrayCastAndSet(dataPtr, (bool) reftype, elmlen, VARDATA(v));
1146 * if (n < VARSIZE(v) - VARHDRSZ) RETURN_NULL;
1150 return (char *) array;
1154 offset = offset * elmlen;
1155 /* off the end of the array */
1156 if (nbytes - offset < 1)
1157 return (char *) array;
1158 pos = ARR_DATA_PTR(array) + offset;
1162 ArrayType *newarray;
1172 elt_ptr = array_seek(ARR_DATA_PTR(array), -1, offset);
1173 oldlen = INTALIGN(*(int32 *) elt_ptr);
1174 newlen = INTALIGN(*(int32 *) dataPtr);
1176 if (oldlen == newlen)
1178 /* new element with same size, overwrite old data */
1179 ArrayCastAndSet(dataPtr, (bool) reftype, elmlen, elt_ptr);
1180 return (char *) array;
1183 /* new element with different size, reallocate the array */
1184 oldsize = array->size;
1185 lth0 = ARR_OVERHEAD(n);
1186 lth1 = (int) (elt_ptr - ARR_DATA_PTR(array));
1187 lth2 = (int) (oldsize - lth0 - lth1 - oldlen);
1188 newsize = lth0 + lth1 + newlen + lth2;
1190 newarray = (ArrayType *) palloc(newsize);
1191 memmove((char *) newarray, (char *) array, lth0 + lth1);
1192 newarray->size = newsize;
1193 newlen = ArrayCastAndSet(dataPtr, (bool) reftype, elmlen,
1194 (char *) newarray + lth0 + lth1);
1195 memmove((char *) newarray + lth0 + lth1 + newlen,
1196 (char *) array + lth0 + lth1 + oldlen, lth2);
1198 /* ??? who should free this storage ??? */
1199 return (char *) newarray;
1201 ArrayCastAndSet(dataPtr, (bool) reftype, elmlen, pos);
1202 return (char *) array;
1205 /*----------------------------------------------------------------------------
1207 * This routine sets the value of a range of array locations (specified
1208 * by upper and lower index values ) to new values passed as
1211 * returns a pointer to the modified array.
1212 *----------------------------------------------------------------------------
1215 array_assgn(ArrayType *array,
1229 if (array == (ArrayType *) NULL)
1232 elog(ERROR, "array_assgn:updates on arrays of variable length elements not allowed");
1234 dim = ARR_DIMS(array);
1235 lb = ARR_LBOUND(array);
1236 ndim = ARR_NDIM(array);
1238 if (!SanityCheckInput(ndim, n, dim, lb, upperIndx) ||
1239 !SanityCheckInput(ndim, n, dim, lb, lowerIndx))
1240 return (char *) array;
1242 for (i = 0; i < n; i++)
1243 if (lowerIndx[i] > upperIndx[i])
1244 elog(ERROR, "lowerIndex larger than upperIndx");
1246 if (ARR_IS_LO(array))
1254 lo_name = (char *) ARR_DATA_PTR(array);
1255 if ((fd = LOopen(lo_name, ARR_IS_INV(array) ? INV_WRITE : O_WRONLY)) < 0)
1256 return (char *) array;
1258 if (ARR_IS_LO(newArr))
1261 lo_name = (char *) ARR_DATA_PTR(newArr);
1262 if ((newfd = LOopen(lo_name, ARR_IS_INV(newArr) ? INV_READ : O_RDONLY)) < 0)
1263 return (char *) array;
1265 _LOArrayRange(lowerIndx, upperIndx, len, fd, newfd, array, 1, isNull);
1270 _LOArrayRange(lowerIndx, upperIndx, len, fd, (int) ARR_DATA_PTR(newArr),
1274 return (char *) array;
1276 _ArrayRange(lowerIndx, upperIndx, len, ARR_DATA_PTR(newArr), array, 0);
1277 return (char *) array;
1283 * Map an arbitrary function to an array and return a new array with
1284 * same dimensions and the source elements transformed by fn().
1287 array_map(ArrayType *v,
1315 /* Large objects not yet supported */
1316 if (ARR_IS_LO(v) == true)
1317 elog(ERROR, "array_map: large objects not supported");
1320 if ((nargs < 0) || (nargs > 4))
1321 elog(ERROR, "array_map: invalid nargs: %d", nargs);
1323 /* Copy extra args to local variable */
1324 va_start(ap, nargs);
1325 for (i = 0; i < nargs; i++)
1326 args[i] = (void *) va_arg(ap, char *);
1329 /* Lookup source and result types. Unneeded variables are reused. */
1330 system_cache_lookup(type, false, &inp_typlen, &inp_typbyval,
1331 &typdelim, &typelem, &proc, &typalign);
1332 system_cache_lookup(retType, false, &typlen, &typbyval,
1333 &typdelim, &typelem, &proc, &typalign);
1337 nitems = getNitems(ndim, dim);
1339 /* Check for empty array */
1343 /* Allocate temporary array for new values */
1344 values = (char **) palloc(nitems * sizeof(char *));
1345 MemSet(values, 0, nitems * sizeof(char *));
1347 /* Loop over source data */
1348 s = (char *) ARR_DATA_PTR(v);
1349 for (i = 0; i < nitems; i++)
1351 /* Get source element */
1357 elt = (char *) ((int) (*(char *) s));
1360 elt = (char *) ((int) (*(int16 *) s));
1365 elt = (char *) (*(int32 *) s);
1376 s += INTALIGN(*(int32 *) s);
1380 * Apply the given function to source elt and extra args. nargs is
1381 * the number of extra args taken by fn().
1386 p = (char *) (*fn) (elt);
1389 p = (char *) (*fn) (elt, args[0]);
1392 p = (char *) (*fn) (elt, args[0], args[1]);
1395 p = (char *) (*fn) (elt, args[0], args[1], args[2]);
1399 p = (char *) (*fn) (elt, args[0], args[1], args[2], args[3]);
1403 /* Update values and total result size */
1406 values[i] = (char *) p;
1413 len = ((typlen > 0) ? typlen : INTALIGN(*(int32 *) p));
1414 /* Needed because _CopyArrayEls tries to pfree items */
1417 p = (char *) palloc(len);
1418 memcpy(p, elt, len);
1420 values[i] = (char *) p;
1425 /* Allocate and initialize the result array */
1426 nbytes += ARR_OVERHEAD(ndim);
1427 result = (ArrayType *) palloc(nbytes);
1428 MemSet(result, 0, nbytes);
1430 memcpy((char *) result, (char *) &nbytes, sizeof(int));
1431 memcpy((char *) ARR_NDIM_PTR(result), (char *) &ndim, sizeof(int));
1432 memcpy((char *) ARR_DIMS(result), ARR_DIMS(v), 2 * ndim * sizeof(int));
1434 /* Copy new values into the result array. values is pfreed. */
1435 _CopyArrayEls((char **) values,
1436 ARR_DATA_PTR(result), nitems,
1437 typlen, typalign, typbyval);
1442 /*-----------------------------------------------------------------------------
1444 * compares two arrays for equality
1446 * returns 1 if the arrays are equal, 0 otherwise.
1447 *-----------------------------------------------------------------------------
1450 array_eq(ArrayType *array1, ArrayType *array2)
1452 if ((array1 == NULL) || (array2 == NULL))
1454 if (*(int *) array1 != *(int *) array2)
1456 if (memcmp(array1, array2, *(int *) array1))
1461 /***************************************************************************/
1462 /******************| Support Routines |*****************/
1463 /***************************************************************************/
1465 system_cache_lookup(Oid element_type,
1474 HeapTuple typeTuple;
1475 Form_pg_type typeStruct;
1477 typeTuple = SearchSysCacheTuple(TYPOID,
1478 ObjectIdGetDatum(element_type),
1481 if (!HeapTupleIsValid(typeTuple))
1483 elog(ERROR, "array_out: Cache lookup failed for type %u\n",
1487 typeStruct = (Form_pg_type) GETSTRUCT(typeTuple);
1488 *typlen = typeStruct->typlen;
1489 *typbyval = typeStruct->typbyval;
1490 *typdelim = typeStruct->typdelim;
1491 *typelem = typeStruct->typelem;
1492 *typalign = typeStruct->typalign;
1494 *proc = typeStruct->typinput;
1496 *proc = typeStruct->typoutput;
1500 _ArrayCast(char *value, bool byval, int len)
1507 return (Datum) *value;
1509 return (Datum) *(int16 *) value;
1512 return (Datum) *(int32 *) value;
1514 elog(ERROR, "array_ref: byval and elt len > 4!");
1519 return (Datum) value;
1525 ArrayCastAndSet(char *src,
1539 *dest = DatumGetChar(src);
1542 *(int16 *) dest = DatumGetInt16(src);
1545 *(int32 *) dest = (int32) src;
1550 memmove(dest, src, typlen);
1555 memmove(dest, src, *(int32 *) src);
1556 inc = (INTALIGN(*(int32 *) src));
1563 _AdvanceBy1word(char *str, char **word)
1571 while (isspace(*str))
1574 if ((space = (char *) strchr(str, ' ')) != (char *) NULL)
1587 SanityCheckInput(int ndim, int n, int *dim, int *lb, int *indx)
1591 /* Do Sanity check on input */
1594 for (i = 0; i < ndim; i++)
1595 if ((lb[i] > indx[i]) || (indx[i] >= (dim[i] + lb[i])))
1601 _ArrayRange(int *st,
1621 n = ARR_NDIM(array);
1622 dim = ARR_DIMS(array);
1623 lb = ARR_LBOUND(array);
1624 srcPtr = ARR_DATA_PTR(array);
1625 for (i = 0; i < n; st[i] -= lb[i], endp[i] -= lb[i], i++);
1626 mda_get_prod(n, dim, prod);
1627 st_pos = tuple2linear(n, st, prod);
1628 srcPtr = array_seek(srcPtr, bsize, st_pos);
1629 mda_get_range(n, span, st, endp);
1630 mda_get_offset_values(n, dist, prod, span);
1631 for (i = 0; i < n; indx[i++] = 0);
1636 srcPtr = array_seek(srcPtr, bsize, dist[j]);
1638 inc = array_read(destPtr, bsize, 1, srcPtr);
1640 inc = array_read(srcPtr, bsize, 1, destPtr);
1643 } while ((j = next_tuple(i + 1, indx, span)) != -1);
1647 _ArrayClipCount(int *stI, int *endpI, ArrayType *array)
1665 n = ARR_NDIM(array);
1666 dim = ARR_DIMS(array);
1667 lb = ARR_LBOUND(array);
1668 ptr = ARR_DATA_PTR(array);
1669 for (i = 0; i < n; st[i] = stI[i] - lb[i], endp[i] = endpI[i] - lb[i], i++);
1670 mda_get_prod(n, dim, prod);
1671 st_pos = tuple2linear(n, st, prod);
1672 ptr = array_seek(ptr, -1, st_pos);
1673 mda_get_range(n, span, st, endp);
1674 mda_get_offset_values(n, dist, prod, span);
1675 for (i = 0; i < n; indx[i++] = 0);
1679 ptr = array_seek(ptr, -1, dist[j]);
1680 inc = INTALIGN(*(int32 *) ptr);
1683 } while ((j = next_tuple(i + 1, indx, span)) != -1);
1688 array_seek(char *ptr, int eltsize, int nitems)
1693 return ptr + eltsize * nitems;
1694 for (i = 0; i < nitems; i++)
1695 ptr += INTALIGN(*(int32 *) ptr);
1700 array_read(char *destptr, int eltsize, int nitems, char *srcptr)
1708 memmove(destptr, srcptr, eltsize * nitems);
1709 return eltsize * nitems;
1711 for (i = inc = 0; i < nitems; i++)
1713 tmp = (INTALIGN(*(int32 *) srcptr));
1714 memmove(destptr, srcptr, tmp);
1723 _LOArrayRange(int *st,
1746 n = ARR_NDIM(array);
1747 dim = ARR_DIMS(array);
1748 lb = ARR_LBOUND(array);
1749 for (i = 0; i < n; st[i] -= lb[i], endp[i] -= lb[i], i++);
1751 mda_get_prod(n, dim, prod);
1752 st_pos = tuple2linear(n, st, prod);
1753 offset = st_pos * bsize;
1754 if (lo_lseek(srcfd, offset, SEEK_SET) < 0)
1756 mda_get_range(n, span, st, endp);
1757 mda_get_offset_values(n, dist, prod, span);
1758 for (i = 0; i < n; indx[i++] = 0);
1759 for (i = n - 1, inc = bsize; i >= 0; inc *= span[i--])
1765 offset += (dist[j] * bsize);
1766 if (lo_lseek(srcfd, offset, SEEK_SET) < 0)
1768 tmp = _LOtransfer((char **) &srcfd, inc, 1, (char **) &destfd, isSrcLO, 1);
1772 } while ((j = next_tuple(i + 1, indx, span)) != -1);
1800 n = ARR_NDIM(array);
1801 dim = ARR_DIMS(array);
1802 lb = ARR_LBOUND(array);
1803 for (i = 0; i < n; st[i] -= lb[i], endp[i] -= lb[i], i++);
1805 mda_get_prod(n, dim, prod);
1806 st_pos = tuple2linear(n, st, prod);
1807 offset = st_pos * bsize;
1808 if (lo_lseek(srcfd, offset, SEEK_SET) < 0)
1810 mda_get_range(n, span, st, endp);
1811 mda_get_offset_values(n, dist, prod, span);
1812 for (i = 0; i < n; indx[i++] = 0);
1813 for (i = n - 1, inc = bsize; i >= 0; inc *= span[i--])
1819 offset += (dist[j] * bsize);
1820 if (lo_lseek(srcfd, offset, SEEK_SET) < 0)
1822 tmp = _LOtransfer((char **) &destfd, inc, 1, (char **) &srcfd, 1, isDestLO);
1826 } while ((j = next_tuple(i + 1, indx, span)) != -1);
1831 _LOtransfer(char **destfd,
1838 #define MAX_READ (512 * 1024)
1839 #define min(a, b) (a < b ? a : b)
1840 struct varlena *v = NULL;
1845 inc = nitems * size;
1846 if (isSrcLO && isDestLO && inc > 0)
1847 for (tmp = 0, resid = inc;
1848 resid > 0 && (inc = min(resid, MAX_READ)) > 0; resid -= inc)
1851 v = (struct varlena *) LOread((int) *srcfd, inc);
1852 if (VARSIZE(v) - VARHDRSZ < inc)
1857 tmp += LOwrite((int) *destfd, v);
1862 else if (!isSrcLO && isDestLO)
1864 tmp = lo_write((int) *destfd, *srcfd, inc);
1865 *srcfd = *srcfd + tmp;
1867 else if (isSrcLO && !isDestLO)
1869 tmp = lo_read((int) *srcfd, *destfd, inc);
1870 *destfd = *destfd + tmp;
1874 memmove(*destfd, *srcfd, inc);
1884 _array_newLO(int *fd, int flag)
1887 char saveName[NAME_LEN];
1889 p = (char *) palloc(NAME_LEN);
1890 sprintf(p, "/Arry.%u", newoid());
1891 strcpy(saveName, p);
1893 if ((*fd = LOcreat(saveName, 0600, flag)) < 0)
1894 elog(ERROR, "Large object create failed");