LCOV - code coverage report
Current view: top level - gdk - gdk_bat.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 1258 1697 74.1 %
Date: 2024-11-12 21:42:17 Functions: 36 41 87.8 %

          Line data    Source code
       1             : /*
       2             :  * SPDX-License-Identifier: MPL-2.0
       3             :  *
       4             :  * This Source Code Form is subject to the terms of the Mozilla Public
       5             :  * License, v. 2.0.  If a copy of the MPL was not distributed with this
       6             :  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
       7             :  *
       8             :  * Copyright 2024 MonetDB Foundation;
       9             :  * Copyright August 2008 - 2023 MonetDB B.V.;
      10             :  * Copyright 1997 - July 2008 CWI.
      11             :  */
      12             : 
      13             : /*
      14             :  * @a M. L. Kersten, P. Boncz, N. Nes
      15             :  * @* BAT Module
      16             :  * In this Chapter we describe the BAT implementation in more detail.
      17             :  * The routines mentioned are primarily meant to simplify the library
      18             :  * implementation.
      19             :  *
      20             :  * @+ BAT Construction
      21             :  * BATs are implemented in several blocks of memory, prepared for disk
      22             :  * storage and easy shipment over a network.
      23             :  *
      24             :  * The BAT starts with a descriptor, which indicates the required BAT
      25             :  * library version and the BAT administration details.  In particular,
      26             :  * it describes the binary relationship maintained and the location of
      27             :  * fields required for storage.
      28             :  *
      29             :  * The general layout of the BAT in this implementation is as follows.
      30             :  * Each BAT comes with a heap for the loc-size buns and, optionally,
      31             :  * with heaps to manage the variable-sized data items of both
      32             :  * dimensions.  The buns are assumed to be stored as loc-size objects.
      33             :  * This is essentially an array of structs to store the associations.
      34             :  * The size is determined at BAT creation time using an upper bound on
      35             :  * the number of elements to be accommodated.  In case of overflow,
      36             :  * its storage space is extended automatically.
      37             :  *
      38             :  * The capacity of a BAT places an upper limit on the number of BUNs
      39             :  * to be stored initially. The actual space set aside may be quite
      40             :  * large.  Moreover, the size is aligned to int boundaries to speedup
      41             :  * access and avoid some machine limitations.
      42             :  *
      43             :  * Initialization of the variable parts rely on type specific routines
      44             :  * called atomHeap.
      45             :  */
      46             : #include "monetdb_config.h"
      47             : #include "gdk.h"
      48             : #include "gdk_private.h"
      49             : #include "mutils.h"
      50             : 
      51             : #ifdef ALIGN
      52             : #undef ALIGN
      53             : #endif
      54             : #define ALIGN(n,b)      ((b)?(b)*(1+(((n)-1)/(b))):n)
      55             : 
      56             : #define ATOMneedheap(tpe) (BATatoms[tpe].atomHeap != NULL)
      57             : 
      58             : BAT *
      59    19611905 : BATcreatedesc(oid hseq, int tt, bool heapnames, role_t role, uint16_t width)
      60             : {
      61    19611905 :         bat bid;
      62    19611905 :         BAT *bn;
      63    19611905 :         Heap *h = NULL, *vh = NULL;
      64             : 
      65             :         /*
      66             :          * Alloc space for the BAT and its dependent records.
      67             :          */
      68    19611905 :         assert(tt >= 0);
      69             : 
      70    19611905 :         if (heapnames) {
      71     9513003 :                 if ((h = GDKmalloc(sizeof(Heap))) == NULL) {
      72             :                         return NULL;
      73             :                 }
      74    19023542 :                 *h = (Heap) {
      75     9512323 :                         .farmid = BBPselectfarm(role, tt, offheap),
      76             :                         .dirty = true,
      77             :                         .refs = ATOMIC_VAR_INIT(1),
      78             :                 };
      79             : 
      80     9511219 :                 if (ATOMneedheap(tt)) {
      81      746695 :                         if ((vh = GDKmalloc(sizeof(Heap))) == NULL) {
      82           0 :                                 GDKfree(h);
      83           0 :                                 return NULL;
      84             :                         }
      85      746518 :                         *vh = (Heap) {
      86      746562 :                                 .farmid = BBPselectfarm(role, tt, varheap),
      87             :                                 .dirty = true,
      88             :                                 .refs = ATOMIC_VAR_INIT(1),
      89             :                         };
      90             :                 }
      91             :         }
      92             : 
      93    19609944 :         bid = BBPallocbat(tt);
      94    19607552 :         if (bid == 0) {
      95           0 :                 GDKfree(h);
      96           0 :                 GDKfree(vh);
      97           0 :                 return NULL;
      98             :         }
      99    19607552 :         bn = BBP_desc(bid);
     100             : 
     101             :         /*
     102             :          * Fill in basic column info
     103             :          */
     104    39221141 :         *bn = (BAT) {
     105             :                 .batCacheid = bid,
     106             :                 .hseqbase = hseq,
     107             : 
     108             :                 .ttype = tt,
     109             :                 .tkey = true,
     110             :                 .tnonil = true,
     111             :                 .tnil = false,
     112    19613589 :                 .tsorted = ATOMlinear(tt),
     113             :                 .trevsorted = ATOMlinear(tt),
     114    19613589 :                 .tascii = tt == TYPE_str,
     115             :                 .tseqbase = oid_nil,
     116             :                 .tminpos = BUN_NONE,
     117             :                 .tmaxpos = BUN_NONE,
     118             :                 .tunique_est = 0.0,
     119             : 
     120             :                 .batRole = role,
     121             :                 .batTransient = true,
     122             :                 .batRestricted = BAT_WRITE,
     123             :                 .theap = h,
     124             :                 .tvheap = vh,
     125    19607552 :                 .creator_tid = MT_getpid(),
     126             :         };
     127             : 
     128    19613589 :         if (bn->theap) {
     129     9513255 :                 bn->theap->parentid = bn->batCacheid;
     130     9513255 :                 const char *nme = BBP_physical(bn->batCacheid);
     131     9513255 :                 settailname(bn->theap, nme, tt, width);
     132             : 
     133     9511092 :                 if (bn->tvheap) {
     134      746574 :                         bn->tvheap->parentid = bn->batCacheid;
     135      746574 :                         strconcat_len(bn->tvheap->filename,
     136             :                                       sizeof(bn->tvheap->filename),
     137             :                                       nme, ".theap", NULL);
     138             :                 }
     139             :         }
     140    19611304 :         char name[MT_NAME_LEN];
     141    19611304 :         snprintf(name, sizeof(name), "heaplock%d", bn->batCacheid); /* fits */
     142    19611304 :         MT_lock_init(&bn->theaplock, name);
     143    19610270 :         snprintf(name, sizeof(name), "BATlock%d", bn->batCacheid); /* fits */
     144    19610270 :         MT_lock_init(&bn->batIdxLock, name);
     145    19612790 :         snprintf(name, sizeof(name), "hashlock%d", bn->batCacheid); /* fits */
     146    19612790 :         MT_rwlock_init(&bn->thashlock, name);
     147    19613709 :         return bn;
     148             : }
     149             : 
     150             : uint8_t
     151    19055665 : ATOMelmshift(int sz)
     152             : {
     153    19055665 :         uint8_t sh;
     154    19055665 :         int i = sz >> 1;
     155             : 
     156    36141058 :         for (sh = 0; i != 0; sh++) {
     157    17085393 :                 i >>= 1;
     158             :         }
     159    19055665 :         return sh;
     160             : }
     161             : 
     162             : 
     163             : void
     164     9517733 : BATsetdims(BAT *b, uint16_t width)
     165             : {
     166     9517733 :         b->twidth = b->ttype == TYPE_str ? width > 0 ? width : 1 : ATOMsize(b->ttype);
     167     9517733 :         b->tshift = ATOMelmshift(b->twidth);
     168     9517733 :         assert_shift_width(b->tshift, b->twidth);
     169     9517733 : }
     170             : 
     171             : const char *
     172        1260 : BATtailname(const BAT *b)
     173             : {
     174        1260 :         if (b->ttype == TYPE_str) {
     175         340 :                 switch (b->twidth) {
     176         250 :                 case 1:
     177         250 :                         return "tail1";
     178          75 :                 case 2:
     179          75 :                         return "tail2";
     180          15 :                 case 4:
     181             : #if SIZEOF_VAR_T == 8
     182          15 :                         return "tail4";
     183             :                 case 8:
     184             : #endif
     185             :                         break;
     186             :                 default:
     187           0 :                         MT_UNREACHABLE();
     188             :                 }
     189             :         }
     190             :         return "tail";
     191             : }
     192             : 
     193             : void
     194     9576590 : settailname(Heap *restrict tail, const char *restrict physnme, int tt, int width)
     195             : {
     196     9576590 :         if (tt == TYPE_str) {
     197      777995 :                 switch (width) {
     198      724750 :                 case 0:
     199             :                 case 1:
     200      724750 :                         strconcat_len(tail->filename,
     201             :                                       sizeof(tail->filename), physnme,
     202             :                                       ".tail1", NULL);
     203      724750 :                         return;
     204       48765 :                 case 2:
     205       48765 :                         strconcat_len(tail->filename,
     206             :                                       sizeof(tail->filename), physnme,
     207             :                                       ".tail2", NULL);
     208       48765 :                         return;
     209        4480 :                 case 4:
     210             : #if SIZEOF_VAR_T == 8
     211        4480 :                         strconcat_len(tail->filename,
     212             :                                       sizeof(tail->filename), physnme,
     213             :                                       ".tail4", NULL);
     214        4480 :                         return;
     215             :                 case 8:
     216             : #endif
     217             :                         break;
     218             :                 default:
     219           0 :                         MT_UNREACHABLE();
     220             :                 }
     221             :         }
     222     8798595 :         strconcat_len(tail->filename, sizeof(tail->filename), physnme,
     223             :                       ".tail", NULL);
     224             : }
     225             : 
     226             : /*
     227             :  * @- BAT allocation
     228             :  * Allocate BUN heap and variable-size atomheaps (see e.g. strHeap).
     229             :  * We now initialize new BATs with their heapname such that the
     230             :  * modified HEAPalloc/HEAPextend primitives can possibly use memory
     231             :  * mapped files as temporary heap storage.
     232             :  *
     233             :  * In case of huge bats, we want HEAPalloc to write a file to disk,
     234             :  * and memory map it. To make this possible, we must provide it with
     235             :  * filenames.
     236             :  */
     237             : BAT *
     238     9512563 : COLnew2(oid hseq, int tt, BUN cap, role_t role, uint16_t width)
     239             : {
     240     9512563 :         BAT *bn;
     241             : 
     242     9512563 :         assert(cap <= BUN_MAX);
     243     9512563 :         assert(hseq <= oid_nil);
     244     9512563 :         ERRORcheck((tt < 0) || (tt > GDKatomcnt), "tt error\n", NULL);
     245             : 
     246             :         /* round up to multiple of BATTINY */
     247     9512563 :         if (cap < BUN_MAX - BATTINY)
     248     9512553 :                 cap = (cap + BATTINY - 1) & ~(BATTINY - 1);
     249     9512563 :         if (ATOMstorage(tt) == TYPE_msk) {
     250      155828 :                 if (cap < 8*BATTINY)
     251             :                         cap = 8*BATTINY;
     252             :                 else
     253       56119 :                         cap = (cap + 31) & ~(BUN)31;
     254     9356735 :         } else if (cap < BATTINY)
     255             :                 cap = BATTINY;
     256             :         /* limit the size */
     257     3303611 :         if (cap > BUN_MAX)
     258             :                 cap = BUN_MAX;
     259             : 
     260     9512563 :         bn = BATcreatedesc(hseq, tt, true, role, width);
     261     9512236 :         if (bn == NULL)
     262             :                 return NULL;
     263             : 
     264     9512236 :         BATsetdims(bn, width);
     265     9512247 :         bn->batCapacity = cap;
     266             : 
     267     9512247 :         if (ATOMstorage(tt) == TYPE_msk)
     268      155828 :                 cap /= 8;       /* 8 values per byte */
     269             : 
     270             :         /* alloc the main heaps */
     271     9512247 :         if (tt && HEAPalloc(bn->theap, cap, bn->twidth) != GDK_SUCCEED) {
     272           0 :                 goto bailout;
     273             :         }
     274             : 
     275     9510318 :         if (bn->tvheap && width == 0 && ATOMheap(tt, bn->tvheap, cap) != GDK_SUCCEED) {
     276           0 :                 HEAPfree(bn->theap, true);
     277           0 :                 goto bailout;
     278             :         }
     279     9510245 :         DELTAinit(bn);
     280     9511002 :         if (BBPcacheit(bn, true) != GDK_SUCCEED) {
     281             :                 /* cannot happen, function always returns success */
     282           0 :                 goto bailout;
     283             :         }
     284     9511217 :         TRC_DEBUG(ALGO, "-> " ALGOBATFMT "\n", ALGOBATPAR(bn));
     285             :         return bn;
     286           0 :   bailout:
     287           0 :         BBPclear(bn->batCacheid);
     288           0 :         return NULL;
     289             : }
     290             : 
     291             : BAT *
     292     9263560 : COLnew(oid hseq, int tt, BUN cap, role_t role)
     293             : {
     294     9263560 :         return COLnew2(hseq, tt, cap, role, 0);
     295             : }
     296             : 
     297             : BAT *
     298     4401289 : BATdense(oid hseq, oid tseq, BUN cnt)
     299             : {
     300     4401289 :         BAT *bn;
     301             : 
     302     4401289 :         bn = COLnew(hseq, TYPE_void, 0, TRANSIENT);
     303     4400834 :         if (bn != NULL) {
     304     4400834 :                 BATtseqbase(bn, tseq);
     305     4400913 :                 BATsetcount(bn, cnt);
     306     4400743 :                 TRC_DEBUG(ALGO, OIDFMT "," OIDFMT "," BUNFMT
     307             :                           "-> " ALGOBATFMT "\n", hseq, tseq, cnt,
     308             :                           ALGOBATPAR(bn));
     309             :         }
     310     4400743 :         return bn;
     311             : }
     312             : 
     313             : BAT *
     314           0 : BATattach(int tt, const char *heapfile, role_t role)
     315             : {
     316           0 :         BAT *bn;
     317           0 :         char *p;
     318           0 :         size_t m;
     319           0 :         FILE *f;
     320             : 
     321           0 :         ERRORcheck(tt <= 0 , "bad tail type (<=0)\n", NULL);
     322           0 :         ERRORcheck(ATOMvarsized(tt) && ATOMstorage(tt) != TYPE_str, "bad tail type (varsized and not str)\n", NULL);
     323           0 :         ERRORcheck(heapfile == NULL, "bad heapfile name\n", NULL);
     324             : 
     325           0 :         if ((f = MT_fopen(heapfile, "rb")) == NULL) {
     326           0 :                 GDKsyserror("BATattach: cannot open %s\n", heapfile);
     327           0 :                 return NULL;
     328             :         }
     329           0 :         if (ATOMstorage(tt) == TYPE_str) {
     330           0 :                 size_t n;
     331           0 :                 char *s;
     332           0 :                 int c, u;
     333             : 
     334           0 :                 if ((bn = COLnew(0, tt, 0, role)) == NULL) {
     335           0 :                         fclose(f);
     336           0 :                         return NULL;
     337             :                 }
     338           0 :                 m = 4096;
     339           0 :                 n = 0;
     340           0 :                 u = 0;
     341           0 :                 s = p = GDKmalloc(m);
     342           0 :                 if (p == NULL) {
     343           0 :                         fclose(f);
     344           0 :                         BBPreclaim(bn);
     345           0 :                         return NULL;
     346             :                 }
     347           0 :                 while ((c = getc(f)) != EOF) {
     348           0 :                         if (n == m) {
     349           0 :                                 m += 4096;
     350           0 :                                 s = GDKrealloc(p, m);
     351           0 :                                 if (s == NULL) {
     352           0 :                                         GDKfree(p);
     353           0 :                                         BBPreclaim(bn);
     354           0 :                                         fclose(f);
     355           0 :                                         return NULL;
     356             :                                 }
     357           0 :                                 p = s;
     358           0 :                                 s = p + n;
     359             :                         }
     360           0 :                         if (c == '\n' && n > 0 && s[-1] == '\r') {
     361             :                                 /* deal with CR-LF sequence */
     362           0 :                                 s[-1] = c;
     363             :                         } else {
     364           0 :                                 *s++ = c;
     365           0 :                                 n++;
     366             :                         }
     367           0 :                         if (u) {
     368           0 :                                 if ((c & 0xC0) == 0x80)
     369           0 :                                         u--;
     370             :                                 else
     371           0 :                                         goto notutf8;
     372           0 :                         } else if ((c & 0xF8) == 0xF0)
     373             :                                 u = 3;
     374           0 :                         else if ((c & 0xF0) == 0xE0)
     375             :                                 u = 2;
     376           0 :                         else if ((c & 0xE0) == 0xC0)
     377             :                                 u = 1;
     378           0 :                         else if ((c & 0x80) == 0x80)
     379           0 :                                 goto notutf8;
     380           0 :                         else if (c == 0) {
     381           0 :                                 if (BUNappend(bn, p, false) != GDK_SUCCEED) {
     382           0 :                                         BBPreclaim(bn);
     383           0 :                                         fclose(f);
     384           0 :                                         GDKfree(p);
     385           0 :                                         return NULL;
     386             :                                 }
     387             :                                 s = p;
     388             :                                 n = 0;
     389             :                         }
     390             :                 }
     391           0 :                 fclose(f);
     392           0 :                 GDKfree(p);
     393           0 :                 if (n > 0) {
     394           0 :                         BBPreclaim(bn);
     395           0 :                         GDKerror("last string is not null-terminated\n");
     396           0 :                         return NULL;
     397             :                 }
     398             :         } else {
     399           0 :                 struct stat st;
     400           0 :                 int atomsize;
     401           0 :                 BUN cap;
     402           0 :                 lng n;
     403             : 
     404           0 :                 if (fstat(fileno(f), &st) < 0) {
     405           0 :                         GDKsyserror("BATattach: cannot stat %s\n", heapfile);
     406           0 :                         fclose(f);
     407           0 :                         return NULL;
     408             :                 }
     409           0 :                 atomsize = ATOMsize(tt);
     410           0 :                 if (st.st_size % atomsize != 0) {
     411           0 :                         fclose(f);
     412           0 :                         GDKerror("heapfile size not integral number of atoms\n");
     413           0 :                         return NULL;
     414             :                 }
     415           0 :                 if (ATOMstorage(tt) == TYPE_msk ?
     416             :                     (st.st_size > (off_t) (BUN_MAX / 8)) :
     417           0 :                     ((size_t) (st.st_size / atomsize) > (size_t) BUN_MAX)) {
     418           0 :                         fclose(f);
     419           0 :                         GDKerror("heapfile too large\n");
     420           0 :                         return NULL;
     421             :                 }
     422           0 :                 cap = (BUN) (ATOMstorage(tt) == TYPE_msk ?
     423           0 :                              st.st_size * 8 :
     424           0 :                              st.st_size / atomsize);
     425           0 :                 bn = COLnew(0, tt, cap, role);
     426           0 :                 if (bn == NULL) {
     427           0 :                         fclose(f);
     428           0 :                         return NULL;
     429             :                 }
     430           0 :                 p = Tloc(bn, 0);
     431           0 :                 n = (lng) st.st_size;
     432           0 :                 while (n > 0 && (m = fread(p, 1, (size_t) MIN(1024*1024, n), f)) > 0) {
     433           0 :                         p += m;
     434           0 :                         n -= m;
     435             :                 }
     436           0 :                 fclose(f);
     437           0 :                 if (n > 0) {
     438           0 :                         GDKerror("couldn't read the complete file\n");
     439           0 :                         BBPreclaim(bn);
     440           0 :                         return NULL;
     441             :                 }
     442           0 :                 BATsetcount(bn, cap);
     443           0 :                 bn->tnonil = cap == 0;
     444           0 :                 bn->tnil = false;
     445           0 :                 bn->tseqbase = oid_nil;
     446           0 :                 if (cap > 1) {
     447           0 :                         bn->tsorted = false;
     448           0 :                         bn->trevsorted = false;
     449           0 :                         bn->tkey = false;
     450             :                 } else {
     451           0 :                         bn->tsorted = ATOMlinear(tt);
     452           0 :                         bn->trevsorted = ATOMlinear(tt);
     453           0 :                         bn->tkey = true;
     454             :                 }
     455             :         }
     456             :         return bn;
     457             : 
     458           0 :   notutf8:
     459           0 :         fclose(f);
     460           0 :         BBPreclaim(bn);
     461           0 :         GDKfree(p);
     462           0 :         GDKerror("input is not UTF-8\n");
     463           0 :         return NULL;
     464             : }
     465             : 
     466             : /*
     467             :  * If the BAT runs out of storage for BUNS it will reallocate space.
     468             :  * For memory mapped BATs we simple extend the administration after
     469             :  * having an assurance that the BAT still can be safely stored away.
     470             :  */
     471             : BUN
     472       22214 : BATgrows(BAT *b)
     473             : {
     474       22214 :         BUN oldcap, newcap;
     475             : 
     476       22214 :         BATcheck(b, 0);
     477             : 
     478       22214 :         newcap = oldcap = BATcapacity(b);
     479       22214 :         if (newcap < BATTINY)
     480             :                 newcap = 2 * BATTINY;
     481       22214 :         else if (newcap < 10 * BATTINY)
     482       20951 :                 newcap = 4 * newcap;
     483        1263 :         else if (newcap < 50 * BATTINY)
     484         778 :                 newcap = 2 * newcap;
     485         485 :         else if ((double) newcap * BATMARGIN <= (double) BUN_MAX)
     486         485 :                 newcap = (BUN) ((double) newcap * BATMARGIN);
     487             :         else
     488             :                 newcap = BUN_MAX;
     489       22214 :         if (newcap == oldcap) {
     490           0 :                 if (newcap <= BUN_MAX - 10)
     491           0 :                         newcap += 10;
     492             :                 else
     493             :                         newcap = BUN_MAX;
     494             :         }
     495       22214 :         if (ATOMstorage(b->ttype) == TYPE_msk) /* round up to multiple of 32 */
     496           2 :                 newcap = (newcap + 31) & ~(BUN)31;
     497             :         return newcap;
     498             : }
     499             : 
     500             : /*
     501             :  * The routine should ensure that the BAT keeps its location in the
     502             :  * BAT buffer.
     503             :  *
     504             :  * Overflow in the other heaps are dealt with in the atom routines.
     505             :  * Here we merely copy their references into the new administration
     506             :  * space.
     507             :  */
     508             : gdk_return
     509      182168 : BATextend(BAT *b, BUN newcap)
     510             : {
     511      182168 :         size_t theap_size;
     512      182168 :         gdk_return rc = GDK_SUCCEED;
     513             : 
     514      182168 :         assert(newcap <= BUN_MAX);
     515      182168 :         BATcheck(b, GDK_FAIL);
     516             :         /*
     517             :          * The main issue is to properly predict the new BAT size.
     518             :          * storage overflow. The assumption taken is that capacity
     519             :          * overflow is rare. It is changed only when the position of
     520             :          * the next available BUN surpasses the free area marker.  Be
     521             :          * aware that the newcap should be greater than the old value,
     522             :          * otherwise you may easily corrupt the administration of
     523             :          * malloc.
     524             :          */
     525      182168 :         if (newcap <= BATcapacity(b)) {
     526             :                 return GDK_SUCCEED;
     527             :         }
     528             : 
     529       31949 :         if (ATOMstorage(b->ttype) == TYPE_msk) {
     530        1121 :                 newcap = (newcap + 31) & ~(BUN)31; /* round up to multiple of 32 */
     531        1121 :                 theap_size = (size_t) (newcap / 8); /* in bytes */
     532             :         } else {
     533       30828 :                 theap_size = (size_t) newcap << b->tshift;
     534             :         }
     535             : 
     536       31949 :         MT_lock_set(&b->theaplock);
     537       31928 :         if (b->theap->base) {
     538       31928 :                 TRC_DEBUG(HEAP, "HEAPgrow in BATextend %s %zu %zu\n",
     539             :                           b->theap->filename, b->theap->size, theap_size);
     540       31928 :                 rc = HEAPgrow(&b->theap, theap_size, b->batRestricted == BAT_READ);
     541       31951 :                 if (rc == GDK_SUCCEED)
     542       31951 :                         b->batCapacity = newcap;
     543             :         } else {
     544           0 :                 b->batCapacity = newcap;
     545             :         }
     546       31951 :         MT_lock_unset(&b->theaplock);
     547             : 
     548       31948 :         return rc;
     549             : }
     550             : 
     551             : 
     552             : 
     553             : /*
     554             :  * @+ BAT destruction
     555             :  * BATclear quickly removes all elements from a BAT. It must respect
     556             :  * the transaction rules; so stable elements must be moved to the
     557             :  * "deleted" section of the BAT (they cannot be fully deleted
     558             :  * yet). For the elements that really disappear, we must free
     559             :  * heapspace. As an optimization, in the case of no stable elements, we quickly empty
     560             :  * the heaps by copying a standard small empty image over them.
     561             :  */
     562             : gdk_return
     563         427 : BATclear(BAT *b, bool force)
     564             : {
     565         427 :         BUN p, q;
     566             : 
     567         427 :         BATcheck(b, GDK_FAIL);
     568             : 
     569         427 :         if (!force && b->batInserted > 0) {
     570           0 :                 GDKerror("cannot clear committed BAT\n");
     571           0 :                 return GDK_FAIL;
     572             :         }
     573             : 
     574         427 :         TRC_DEBUG(ALGO, ALGOBATFMT "\n", ALGOBATPAR(b));
     575             : 
     576             :         /* kill all search accelerators */
     577         427 :         HASHdestroy(b);
     578         427 :         OIDXdestroy(b);
     579         427 :         STRMPdestroy(b);
     580         427 :         RTREEdestroy(b);
     581         427 :         PROPdestroy(b);
     582             : 
     583         427 :         bat tvp = 0;
     584             : 
     585             :         /* we must dispose of all inserted atoms */
     586         427 :         MT_lock_set(&b->theaplock);
     587         427 :         if (force && BATatoms[b->ttype].atomDel == NULL) {
     588         420 :                 assert(b->tvheap == NULL || b->tvheap->parentid == b->batCacheid);
     589             :                 /* no stable elements: we do a quick heap clean */
     590             :                 /* need to clean heap which keeps data even though the
     591             :                    BUNs got removed. This means reinitialize when
     592             :                    free > 0
     593             :                 */
     594         420 :                 if (b->tvheap && b->tvheap->free > 0) {
     595          21 :                         Heap *th = GDKmalloc(sizeof(Heap));
     596             : 
     597          21 :                         if (th == NULL) {
     598           0 :                                 MT_lock_unset(&b->theaplock);
     599           0 :                                 return GDK_FAIL;
     600             :                         }
     601          21 :                         *th = (Heap) {
     602          21 :                                 .farmid = b->tvheap->farmid,
     603          21 :                                 .parentid = b->tvheap->parentid,
     604             :                                 .dirty = true,
     605          21 :                                 .hasfile = b->tvheap->hasfile,
     606             :                                 .refs = ATOMIC_VAR_INIT(1),
     607             :                         };
     608          21 :                         strcpy_len(th->filename, b->tvheap->filename, sizeof(th->filename));
     609          21 :                         if (ATOMheap(b->ttype, th, 0) != GDK_SUCCEED) {
     610           0 :                                 MT_lock_unset(&b->theaplock);
     611           0 :                                 return GDK_FAIL;
     612             :                         }
     613          21 :                         tvp = b->tvheap->parentid;
     614          21 :                         HEAPdecref(b->tvheap, false);
     615          21 :                         b->tvheap = th;
     616             :                 }
     617             :         } else {
     618             :                 /* do heap-delete of all inserted atoms */
     619           7 :                 void (*tatmdel)(Heap*,var_t*) = BATatoms[b->ttype].atomDel;
     620             : 
     621             :                 /* TYPE_str has no del method, so we shouldn't get here */
     622           7 :                 assert(tatmdel == NULL || b->twidth == sizeof(var_t));
     623           0 :                 if (tatmdel) {
     624           0 :                         BATiter bi = bat_iterator_nolock(b);
     625             : 
     626           0 :                         for (p = b->batInserted, q = BATcount(b); p < q; p++)
     627           0 :                                 (*tatmdel)(b->tvheap, (var_t*) BUNtloc(bi,p));
     628           0 :                         b->tvheap->dirty = true;
     629             :                 }
     630             :         }
     631             : 
     632         427 :         b->batInserted = 0;
     633         427 :         b->batCount = 0;
     634         427 :         if (b->ttype == TYPE_void)
     635           0 :                 b->batCapacity = 0;
     636         427 :         b->theap->free = 0;
     637         427 :         BAThseqbase(b, 0);
     638         427 :         BATtseqbase(b, ATOMtype(b->ttype) == TYPE_oid ? 0 : oid_nil);
     639         427 :         b->theap->dirty = true;
     640         427 :         b->tnonil = true;
     641         427 :         b->tnil = false;
     642         427 :         b->tsorted = b->trevsorted = ATOMlinear(b->ttype);
     643         427 :         b->tnosorted = b->tnorevsorted = 0;
     644         427 :         b->tkey = true;
     645         427 :         b->tnokey[0] = b->tnokey[1] = 0;
     646         427 :         b->tminpos = b->tmaxpos = BUN_NONE;
     647         427 :         b->tunique_est = 0;
     648         427 :         MT_lock_unset(&b->theaplock);
     649         427 :         if (tvp != 0 && tvp != b->batCacheid)
     650           0 :                 BBPrelease(tvp);
     651             :         return GDK_SUCCEED;
     652             : }
     653             : 
     654             : /* free a cached BAT; leave the bat descriptor cached */
     655             : void
     656      356276 : BATfree(BAT *b)
     657             : {
     658      356276 :         if (b == NULL)
     659             :                 return;
     660             : 
     661             :         /* deallocate all memory for a bat */
     662      356276 :         MT_rwlock_rdlock(&b->thashlock);
     663      356276 :         BUN nunique = BUN_NONE;
     664      356276 :         if (b->thash && b->thash != (Hash *) 1) {
     665        1918 :                 nunique = b->thash->nunique;
     666             :         }
     667      356276 :         MT_rwlock_rdunlock(&b->thashlock);
     668      356276 :         HASHfree(b);
     669      356276 :         OIDXfree(b);
     670      356276 :         STRMPfree(b);
     671      356276 :         RTREEfree(b);
     672      356276 :         MT_lock_set(&b->theaplock);
     673      356276 :         if (nunique != BUN_NONE) {
     674        1918 :                 b->tunique_est = (double) nunique;
     675             :         }
     676             :         /* wait until there are no other references to the heap; a
     677             :          * reference is possible in e.g. BBPsync that uses a
     678             :          * bat_iterator directly on the BBP_desc, i.e. without fix */
     679      356276 :         while (b->theap && (ATOMIC_GET(&b->theap->refs) & HEAPREFS) > 1) {
     680           0 :                 MT_lock_unset(&b->theaplock);
     681           0 :                 MT_sleep_ms(1);
     682      356276 :                 MT_lock_set(&b->theaplock);
     683             :         }
     684      356276 :         if (b->theap) {
     685      356276 :                 assert((ATOMIC_GET(&b->theap->refs) & HEAPREFS) == 1);
     686      356276 :                 assert(b->theap->parentid == b->batCacheid);
     687      356276 :                 HEAPfree(b->theap, false);
     688             :         }
     689             :         /* wait until there are no other references to the heap; a
     690             :          * reference is possible in e.g. BBPsync that uses a
     691             :          * bat_iterator directly on the BBP_desc, i.e. without fix */
     692       31452 :         while (b->tvheap && (ATOMIC_GET(&b->tvheap->refs) & HEAPREFS) > 1) {
     693           0 :                 MT_lock_unset(&b->theaplock);
     694           0 :                 MT_sleep_ms(1);
     695      356276 :                 MT_lock_set(&b->theaplock);
     696             :         }
     697      356276 :         if (b->tvheap) {
     698       31452 :                 assert((ATOMIC_GET(&b->tvheap->refs) & HEAPREFS) == 1);
     699       31452 :                 assert(b->tvheap->parentid == b->batCacheid);
     700       31452 :                 HEAPfree(b->tvheap, false);
     701             :         }
     702      356276 :         MT_lock_unset(&b->theaplock);
     703             : }
     704             : 
     705             : /* free a cached BAT descriptor */
     706             : void
     707    19640797 : BATdestroy(BAT *b)
     708             : {
     709    19640797 :         if (b->tvheap) {
     710       29574 :                 GDKfree(b->tvheap);
     711             :         }
     712    19640797 :         PROPdestroy_nolock(b);
     713    19640466 :         MT_lock_destroy(&b->theaplock);
     714    19638454 :         MT_lock_destroy(&b->batIdxLock);
     715    19638755 :         MT_rwlock_destroy(&b->thashlock);
     716    19639225 :         if (b->theap) {
     717      350012 :                 GDKfree(b->theap);
     718             :         }
     719    19637727 :         if (b->oldtail) {
     720           0 :                 ATOMIC_AND(&b->oldtail->refs, ~DELAYEDREMOVE);
     721             :                 /* the bat has not been committed, so we cannot remove
     722             :                  * the old tail file */
     723           0 :                 HEAPdecref(b->oldtail, false);
     724           0 :                 b->oldtail = NULL;
     725             :         }
     726    19637727 :         *b = (BAT) {
     727             :                 .batCacheid = 0,
     728             :         };
     729    19637727 : }
     730             : 
     731             : /*
     732             :  * @+ BAT copying
     733             :  *
     734             :  * BAT copying is an often used operation. So it deserves attention.
     735             :  * When making a copy of a BAT, the following aspects are of
     736             :  * importance:
     737             :  *
     738             :  * - the requested head and tail types. The purpose of the copy may be
     739             :  *   to slightly change these types (e.g. void <-> oid). We may also
     740             :  *   remap between types as long as they share the same
     741             :  *   ATOMstorage(type), i.e. the types have the same physical
     742             :  *   implementation. We may even want to allow 'dirty' trick such as
     743             :  *   viewing a flt-column suddenly as int.
     744             :  *
     745             :  *   To allow such changes, the desired column-types is a
     746             :  *   parameter of COLcopy.
     747             :  *
     748             :  * - access mode. If we want a read-only copy of a read-only BAT, a
     749             :  *   VIEW may do (in this case, the user may be after just an
     750             :  *   independent BAT header and id). This is indicated by the
     751             :  *   parameter (writable = FALSE).
     752             :  *
     753             :  *   In other cases, we really want an independent physical copy
     754             :  *   (writable = TRUE).  Changing the mode to BAT_WRITE will be a
     755             :  *   zero-cost operation if the BAT was copied with (writable = TRUE).
     756             :  *
     757             :  * In GDK, the result is a BAT that is BAT_WRITE iff (writable ==
     758             :  * TRUE).
     759             :  *
     760             :  * In these cases the copy becomes a logical view on the original,
     761             :  * which ensures that the original cannot be modified or destroyed
     762             :  * (which could affect the shared heaps).
     763             :  */
     764             : static bool
     765         404 : wrongtype(int t1, int t2)
     766             : {
     767             :         /* check if types are compatible. be extremely forgiving */
     768         404 :         if (t1 != TYPE_void) {
     769         404 :                 t1 = ATOMtype(ATOMstorage(t1));
     770         404 :                 t2 = ATOMtype(ATOMstorage(t2));
     771         404 :                 if (t1 != t2) {
     772         354 :                         if (ATOMvarsized(t1) ||
     773         354 :                             ATOMvarsized(t2) ||
     774         354 :                             t1 == TYPE_msk || t2 == TYPE_msk ||
     775         354 :                             ATOMsize(t1) != ATOMsize(t2))
     776           0 :                                 return true;
     777             :                 }
     778             :         }
     779             :         return false;
     780             : }
     781             : 
     782             : /*
     783             :  * There are four main implementation cases:
     784             :  * (1) we are allowed to return a view (zero effort),
     785             :  * (2) the result is void,void (zero effort),
     786             :  * (3) we can copy the heaps (memcopy, or even VM page sharing)
     787             :  * (4) we must insert BUN-by-BUN into the result (fallback)
     788             :  * The latter case is still optimized for the case that the result
     789             :  * is bat[void,T] for a simple fixed-size type T. In that case we
     790             :  * do inline array[T] inserts.
     791             :  */
     792             : BAT *
     793       48292 : COLcopy(BAT *b, int tt, bool writable, role_t role)
     794             : {
     795       48292 :         bool slowcopy = false;
     796       48292 :         BAT *bn = NULL;
     797       48292 :         BATiter bi;
     798       48292 :         char strhash[GDK_STRHASHSIZE];
     799             : 
     800       48292 :         BATcheck(b, NULL);
     801             : 
     802             :         /* maybe a bit ugly to change the requested bat type?? */
     803       48292 :         if (b->ttype == TYPE_void && !writable)
     804       48292 :                 tt = TYPE_void;
     805             : 
     806       48292 :         if (tt != b->ttype && wrongtype(tt, b->ttype)) {
     807           0 :                 GDKerror("wrong tail-type requested\n");
     808           0 :                 return NULL;
     809             :         }
     810             : 
     811             :         /* in case of a string bat, we save the string heap hash table
     812             :          * while we have the lock so that we can restore it in the copy;
     813             :          * this is because during our operation, a parallel thread could
     814             :          * be adding strings to the vheap which would modify the hash
     815             :          * table and that would result in buckets containing values
     816             :          * beyond the original vheap that we're copying */
     817       48292 :         MT_lock_set(&b->theaplock);
     818       48292 :         BAT *pb = NULL, *pvb = NULL;
     819       48292 :         if (b->theap->parentid != b->batCacheid) {
     820       10715 :                 pb = BBP_desc(b->theap->parentid);
     821       10715 :                 MT_lock_set(&pb->theaplock);
     822             :         }
     823       48292 :         if (b->tvheap &&
     824       16423 :             b->tvheap->parentid != b->batCacheid &&
     825       11526 :             b->tvheap->parentid != b->theap->parentid) {
     826       10866 :                 pvb = BBP_desc(b->tvheap->parentid);
     827       10866 :                 MT_lock_set(&pvb->theaplock);
     828             :         }
     829       48291 :         bi = bat_iterator_nolock(b);
     830       48291 :         if (ATOMstorage(b->ttype) == TYPE_str && b->tvheap->free >= GDK_STRHASHSIZE)
     831       12175 :                 memcpy(strhash, b->tvheap->base, GDK_STRHASHSIZE);
     832             : 
     833       48291 :         bat_iterator_incref(&bi);
     834       48291 :         if (pvb)
     835       10865 :                 MT_lock_unset(&pvb->theaplock);
     836       48291 :         if (pb)
     837       10715 :                 MT_lock_unset(&pb->theaplock);
     838       48291 :         MT_lock_unset(&b->theaplock);
     839             : 
     840             :         /* first try case (1); create a view, possibly with different
     841             :          * atom-types */
     842       48292 :         if (!writable &&
     843       48292 :             role == TRANSIENT &&
     844       20290 :             bi.restricted == BAT_READ &&
     845       16190 :             ATOMstorage(b->ttype) != TYPE_msk && /* no view on TYPE_msk */
     846       16190 :             (bi.h == NULL ||
     847       16190 :              bi.h->parentid == b->batCacheid ||
     848        3616 :              BBP_desc(bi.h->parentid)->batRestricted == BAT_READ)) {
     849       16190 :                 bn = VIEWcreate(b->hseqbase, b, 0, BUN_MAX);
     850       16190 :                 if (bn == NULL) {
     851           0 :                         goto bunins_failed;
     852             :                 }
     853       16190 :                 if (tt != bn->ttype) {
     854          47 :                         bn->ttype = tt;
     855          47 :                         if (bn->tvheap && !ATOMvarsized(tt)) {
     856           0 :                                 if (bn->tvheap->parentid != bn->batCacheid)
     857           0 :                                         BBPrelease(bn->tvheap->parentid);
     858           0 :                                 HEAPdecref(bn->tvheap, false);
     859           0 :                                 bn->tvheap = NULL;
     860             :                         }
     861          47 :                         bn->tseqbase = ATOMtype(tt) == TYPE_oid ? bi.tseq : oid_nil;
     862             :                 }
     863       16190 :                 bat_iterator_end(&bi);
     864       16190 :                 return bn;
     865             :         } else {
     866             :                 /* check whether we need case (4); BUN-by-BUN copy (by
     867             :                  * setting slowcopy to true) */
     868       32102 :                 if (ATOMsize(tt) != ATOMsize(bi.type)) {
     869             :                         /* oops, void materialization */
     870             :                         slowcopy = true;
     871       31748 :                 } else if (bi.h && bi.h->parentid != b->batCacheid &&
     872        7099 :                            BATcapacity(BBP_desc(bi.h->parentid)) > bi.count + bi.count) {
     873             :                         /* reduced slice view: do not copy too much
     874             :                          * garbage */
     875             :                         slowcopy = true;
     876       24839 :                 } else if (bi.vh && bi.vh->parentid != b->batCacheid &&
     877       10275 :                            BATcount(BBP_desc(bi.vh->parentid)) > bi.count + bi.count) {
     878             :                         /* reduced vheap view: do not copy too much
     879             :                          * garbage; this really is a heuristic since the
     880             :                          * vheap could be used completely, even if the
     881             :                          * offset heap is only (less than) half the size
     882             :                          * of the parent's offset heap */
     883        9447 :                         slowcopy = true;
     884             :                 }
     885             : 
     886       32102 :                 bn = COLnew2(b->hseqbase, tt, bi.count, role, bi.width);
     887       32105 :                 if (bn == NULL) {
     888           0 :                         goto bunins_failed;
     889             :                 }
     890       32105 :                 if (bn->tvheap != NULL && bn->tvheap->base == NULL) {
     891             :                         /* this combination can happen since the last
     892             :                          * argument of COLnew2 not being zero triggers a
     893             :                          * skip in the allocation of the tvheap */
     894       12425 :                         if (ATOMheap(bn->ttype, bn->tvheap, bn->batCapacity) != GDK_SUCCEED) {
     895           0 :                                 goto bunins_failed;
     896             :                         }
     897             :                 }
     898             : 
     899       32100 :                 if (tt == TYPE_void) {
     900             :                         /* case (2): a void,void result => nothing to
     901             :                          * copy! */
     902        1106 :                         bn->theap->free = 0;
     903       30994 :                 } else if (!slowcopy) {
     904             :                         /* case (3): just copy the heaps */
     905       21547 :                         if (bn->tvheap && HEAPextend(bn->tvheap, bi.vhfree, true) != GDK_SUCCEED) {
     906           0 :                                 goto bunins_failed;
     907             :                         }
     908       21546 :                         memcpy(bn->theap->base, bi.base, bi.hfree);
     909       21546 :                         bn->theap->free = bi.hfree;
     910       21546 :                         bn->theap->dirty = true;
     911       21546 :                         if (bn->tvheap) {
     912        9542 :                                 memcpy(bn->tvheap->base, bi.vh->base, bi.vhfree);
     913        9542 :                                 bn->tvheap->free = bi.vhfree;
     914        9542 :                                 bn->tvheap->dirty = true;
     915        9542 :                                 bn->tascii = bi.ascii;
     916        9542 :                                 if (ATOMstorage(b->ttype) == TYPE_str && bi.vhfree >= GDK_STRHASHSIZE)
     917        8712 :                                         memcpy(bn->tvheap->base, strhash, GDK_STRHASHSIZE);
     918             :                         }
     919             : 
     920             :                         /* make sure we use the correct capacity */
     921       21546 :                         if (ATOMstorage(bn->ttype) == TYPE_msk)
     922           0 :                                 bn->batCapacity = (BUN) (bn->theap->size * 8);
     923       21546 :                         else if (bn->ttype)
     924       21546 :                                 bn->batCapacity = (BUN) (bn->theap->size >> bn->tshift);
     925             :                         else
     926           0 :                                 bn->batCapacity = 0;
     927       18894 :                 } else if (tt != TYPE_void || ATOMextern(tt)) {
     928             :                         /* case (4): one-by-one BUN insert (really slow) */
     929        9447 :                         QryCtx *qry_ctx = MT_thread_get_qry_ctx();
     930             : 
     931     8915768 :                         TIMEOUT_LOOP_IDX_DECL(p, bi.count, qry_ctx) {
     932     8896410 :                                 const void *t = BUNtail(bi, p);
     933             : 
     934     8896312 :                                 if (bunfastapp_nocheck(bn, t) != GDK_SUCCEED) {
     935           0 :                                         goto bunins_failed;
     936             :                                 }
     937             :                         }
     938        9447 :                         TIMEOUT_CHECK(qry_ctx, GOTO_LABEL_TIMEOUT_HANDLER(bunins_failed, qry_ctx));
     939        9447 :                         bn->theap->dirty |= bi.count > 0;
     940             :                 } else if (tt != TYPE_void && bi.type == TYPE_void) {
     941             :                         /* case (4): optimized for unary void
     942             :                          * materialization */
     943             :                         oid cur = bi.tseq, *dst = (oid *) Tloc(bn, 0);
     944             :                         const oid inc = !is_oid_nil(cur);
     945             : 
     946             :                         bn->theap->free = bi.count * sizeof(oid);
     947             :                         bn->theap->dirty |= bi.count > 0;
     948             :                         for (BUN p = 0; p < bi.count; p++) {
     949             :                                 dst[p] = cur;
     950             :                                 cur += inc;
     951             :                         }
     952             :                 } else if (ATOMstorage(bi.type) == TYPE_msk) {
     953             :                         /* convert number of bits to number of bytes,
     954             :                          * and round the latter up to a multiple of
     955             :                          * 4 (copy in units of 4 bytes) */
     956             :                         bn->theap->free = ((bi.count + 31) / 32) * 4;
     957             :                         bn->theap->dirty |= bi.count > 0;
     958             :                         memcpy(Tloc(bn, 0), bi.base, bn->theap->free);
     959             :                 } else {
     960             :                         /* case (4): optimized for simple array copy */
     961             :                         bn->theap->free = bi.count << bn->tshift;
     962             :                         bn->theap->dirty |= bi.count > 0;
     963             :                         memcpy(Tloc(bn, 0), bi.base, bn->theap->free);
     964             :                 }
     965             :                 /* copy all properties (size+other) from the source bat */
     966       32099 :                 BATsetcount(bn, bi.count);
     967             :         }
     968             :         /* set properties (note that types may have changed in the copy) */
     969       63845 :         if (ATOMtype(tt) == ATOMtype(bi.type)) {
     970       32097 :                 if (ATOMtype(tt) == TYPE_oid) {
     971        8021 :                         BATtseqbase(bn, bi.tseq);
     972             :                 } else {
     973       24076 :                         BATtseqbase(bn, oid_nil);
     974             :                 }
     975       32099 :                 BATkey(bn, bi.key);
     976       32095 :                 bn->tsorted = bi.sorted;
     977       32095 :                 bn->trevsorted = bi.revsorted;
     978       32095 :                 bn->tnorevsorted = bi.norevsorted;
     979       32095 :                 if (bi.nokey[0] != bi.nokey[1]) {
     980        2626 :                         bn->tnokey[0] = bi.nokey[0];
     981        2626 :                         bn->tnokey[1] = bi.nokey[1];
     982             :                 } else {
     983       29469 :                         bn->tnokey[0] = bn->tnokey[1] = 0;
     984             :                 }
     985       32095 :                 bn->tnosorted = bi.nosorted;
     986       32095 :                 bn->tnonil = bi.nonil;
     987       32095 :                 bn->tnil = bi.nil;
     988       32095 :                 bn->tminpos = bi.minpos;
     989       32095 :                 bn->tmaxpos = bi.maxpos;
     990       32095 :                 bn->tunique_est = bi.unique_est;
     991           3 :         } else if (ATOMstorage(tt) == ATOMstorage(b->ttype) &&
     992           3 :                    ATOMcompare(tt) == ATOMcompare(b->ttype)) {
     993           3 :                 BUN h = bi.count;
     994           3 :                 bn->tsorted = bi.sorted;
     995           3 :                 bn->trevsorted = bi.revsorted;
     996           3 :                 BATkey(bn, bi.key);
     997           3 :                 bn->tnonil = bi.nonil;
     998           3 :                 bn->tnil = bi.nil;
     999           3 :                 if (bi.nosorted > 0 && bi.nosorted < h)
    1000           1 :                         bn->tnosorted = bi.nosorted;
    1001             :                 else
    1002           2 :                         bn->tnosorted = 0;
    1003           3 :                 if (bi.norevsorted > 0 && bi.norevsorted < h)
    1004           3 :                         bn->tnorevsorted = bi.norevsorted;
    1005             :                 else
    1006           0 :                         bn->tnorevsorted = 0;
    1007           3 :                 if (bi.nokey[0] < h &&
    1008           3 :                     bi.nokey[1] < h &&
    1009             :                     bi.nokey[0] != bi.nokey[1]) {
    1010           0 :                         bn->tnokey[0] = bi.nokey[0];
    1011           0 :                         bn->tnokey[1] = bi.nokey[1];
    1012             :                 } else {
    1013           3 :                         bn->tnokey[0] = bn->tnokey[1] = 0;
    1014             :                 }
    1015           3 :                 bn->tminpos = bi.minpos;
    1016           3 :                 bn->tmaxpos = bi.maxpos;
    1017           3 :                 bn->tunique_est = bi.unique_est;
    1018             :         } else {
    1019           0 :                 bn->tsorted = bn->trevsorted = false; /* set based on count later */
    1020           0 :                 bn->tnonil = bn->tnil = false;
    1021           0 :                 bn->tkey = false;
    1022           0 :                 bn->tnosorted = bn->tnorevsorted = 0;
    1023           0 :                 bn->tnokey[0] = bn->tnokey[1] = 0;
    1024             :         }
    1025       32098 :         if (BATcount(bn) <= 1) {
    1026        6015 :                 bn->tsorted = ATOMlinear(b->ttype);
    1027        6015 :                 bn->trevsorted = ATOMlinear(b->ttype);
    1028        6015 :                 bn->tkey = true;
    1029             :         }
    1030       32098 :         bat_iterator_end(&bi);
    1031       32103 :         if (!writable)
    1032        4100 :                 bn->batRestricted = BAT_READ;
    1033       32103 :         TRC_DEBUG(ALGO, ALGOBATFMT " -> " ALGOBATFMT "\n",
    1034             :                   ALGOBATPAR(b), ALGOBATPAR(bn));
    1035             :         return bn;
    1036           0 :       bunins_failed:
    1037           0 :         bat_iterator_end(&bi);
    1038           0 :         BBPreclaim(bn);
    1039             :         return NULL;
    1040             : }
    1041             : 
    1042             : /* Append an array of values of length count to the bat.  For
    1043             :  * fixed-sized values, `values' is an array of values, for
    1044             :  * variable-sized values, `values' is an array of pointers to values.
    1045             :  * If values equals NULL, count times nil will be appended. */
    1046             : gdk_return
    1047    54402265 : BUNappendmulti(BAT *b, const void *values, BUN count, bool force)
    1048             : {
    1049    54402265 :         BUN p;
    1050    54402265 :         BUN nunique = 0;
    1051             : 
    1052    54402265 :         BATcheck(b, GDK_FAIL);
    1053             : 
    1054    54402265 :         assert(!VIEWtparent(b));
    1055             : 
    1056    54402265 :         if (count == 0)
    1057             :                 return GDK_SUCCEED;
    1058             : 
    1059    54404738 :         TRC_DEBUG(ALGO, ALGOBATFMT " appending " BUNFMT " values%s\n", ALGOBATPAR(b), count, values ? "" : " (all nil)");
    1060             : 
    1061    54402062 :         p = BATcount(b);                /* insert at end */
    1062    54402062 :         if (p == BUN_MAX || BATcount(b) + count >= BUN_MAX) {
    1063           0 :                 GDKerror("bat too large\n");
    1064           0 :                 return GDK_FAIL;
    1065             :         }
    1066             : 
    1067    54402062 :         ALIGNapp(b, force, GDK_FAIL);
    1068             :         /* load hash so that we can maintain it */
    1069    54402015 :         (void) BATcheckhash(b);
    1070             : 
    1071    54415597 :         if (b->ttype == TYPE_void && BATtdense(b)) {
    1072           0 :                 const oid *ovals = values;
    1073           0 :                 bool dense = b->batCount == 0 || (ovals != NULL && b->tseqbase + 1 == ovals[0]);
    1074           0 :                 if (ovals) {
    1075           0 :                         for (BUN i = 1; dense && i < count; i++) {
    1076           0 :                                 dense = ovals[i - 1] + 1 == ovals[i];
    1077             :                         }
    1078             :                 }
    1079           0 :                 if (dense) {
    1080           0 :                         MT_lock_set(&b->theaplock);
    1081           0 :                         if (b->batCount == 0)
    1082           0 :                                 b->tseqbase = ovals ? ovals[0] : oid_nil;
    1083           0 :                         BATsetcount(b, BATcount(b) + count);
    1084           0 :                         MT_lock_unset(&b->theaplock);
    1085           0 :                         return GDK_SUCCEED;
    1086             :                 } else {
    1087             :                         /* we need to materialize b; allocate enough capacity */
    1088           0 :                         if (BATmaterialize(b, BATcount(b) + count) != GDK_SUCCEED)
    1089             :                                 return GDK_FAIL;
    1090             :                 }
    1091             :         }
    1092             : 
    1093    54415597 :         if (unshare_varsized_heap(b) != GDK_SUCCEED) {
    1094             :                 return GDK_FAIL;
    1095             :         }
    1096             : 
    1097    54411709 :         if (BATcount(b) + count > BATcapacity(b)) {
    1098             :                 /* if needed space exceeds a normal growth extend just
    1099             :                  * with what's needed */
    1100       11475 :                 BUN ncap = BATcount(b) + count;
    1101       11475 :                 BUN grows = BATgrows(b);
    1102             : 
    1103       11475 :                 if (ncap > grows)
    1104             :                         grows = ncap;
    1105       11475 :                 gdk_return rc = BATextend(b, grows);
    1106       11474 :                 if (rc != GDK_SUCCEED)
    1107             :                         return rc;
    1108             :         }
    1109             : 
    1110    54411708 :         const void *t = b->ttype == TYPE_msk ? &(msk){false} : ATOMnilptr(b->ttype);
    1111    54411708 :         MT_lock_set(&b->theaplock);
    1112    54391650 :         BATiter bi = bat_iterator_nolock(b);
    1113    54391650 :         const ValRecord *prop;
    1114    54391650 :         ValRecord minprop, maxprop;
    1115    54391650 :         const void *minbound = NULL, *maxbound = NULL;
    1116    54391661 :         if ((prop = BATgetprop_nolock(b, GDK_MIN_BOUND)) != NULL &&
    1117          11 :             VALcopy(&minprop, prop) != NULL)
    1118          11 :                 minbound = VALptr(&minprop);
    1119    54419892 :         if ((prop = BATgetprop_nolock(b, GDK_MAX_BOUND)) != NULL &&
    1120          10 :             VALcopy(&maxprop, prop) != NULL)
    1121          10 :                 maxbound = VALptr(&maxprop);
    1122    54416260 :         const bool notnull = BATgetprop_nolock(b, GDK_NOT_NULL) != NULL;
    1123    54408093 :         MT_lock_unset(&b->theaplock);
    1124    54409337 :         MT_rwlock_wrlock(&b->thashlock);
    1125    54421247 :         if (values && b->ttype) {
    1126    54409834 :                 int (*atomcmp) (const void *, const void *) = ATOMcompare(b->ttype);
    1127    54409834 :                 const void *atomnil = ATOMnilptr(b->ttype);
    1128    54409834 :                 const void *minvalp = NULL, *maxvalp = NULL;
    1129    54409834 :                 if (b->tvheap) {
    1130    22026856 :                         if (bi.minpos != BUN_NONE)
    1131    19134981 :                                 minvalp = BUNtvar(bi, bi.minpos);
    1132    22026856 :                         if (bi.maxpos != BUN_NONE)
    1133    19134918 :                                 maxvalp = BUNtvar(bi, bi.maxpos);
    1134    22026856 :                         const void *vbase = b->tvheap->base;
    1135    44067710 :                         for (BUN i = 0; i < count; i++) {
    1136    22041476 :                                 t = ((void **) values)[i];
    1137    22041476 :                                 bool isnil = atomcmp(t, atomnil) == 0;
    1138    22040421 :                                 gdk_return rc;
    1139    22040421 :                                 if (notnull && isnil) {
    1140           0 :                                         assert(0);
    1141             :                                         GDKerror("NULL value not within bounds\n");
    1142             :                                         rc = GDK_FAIL;
    1143    22040421 :                                 } else if (minbound &&
    1144    22040421 :                                            !isnil &&
    1145           0 :                                            atomcmp(t, minbound) < 0) {
    1146           0 :                                         assert(0);
    1147             :                                         GDKerror("value not within bounds\n");
    1148             :                                         rc = GDK_FAIL;
    1149    22040421 :                                 } else if (maxbound &&
    1150           0 :                                            !isnil &&
    1151           0 :                                            atomcmp(t, maxbound) >= 0) {
    1152           0 :                                         assert(0);
    1153             :                                         GDKerror("value not within bounds\n");
    1154             :                                         rc = GDK_FAIL;
    1155             :                                 } else {
    1156    22040421 :                                         rc = tfastins_nocheckVAR(b, p, t);
    1157             :                                 }
    1158    22042887 :                                 if (rc != GDK_SUCCEED) {
    1159           0 :                                         MT_rwlock_wrunlock(&b->thashlock);
    1160           0 :                                         if (minbound)
    1161           0 :                                                 VALclear(&minprop);
    1162           0 :                                         if (maxbound)
    1163           0 :                                                 VALclear(&maxprop);
    1164           0 :                                         return rc;
    1165             :                                 }
    1166    22042887 :                                 if (vbase != b->tvheap->base) {
    1167             :                                         /* tvheap changed location, so
    1168             :                                          * pointers may need to be
    1169             :                                          * updated (not if they were
    1170             :                                          * initialized from t below, but
    1171             :                                          * we don't know) */
    1172        3385 :                                         BUN minpos = bi.minpos;
    1173        3385 :                                         BUN maxpos = bi.maxpos;
    1174        3385 :                                         MT_lock_set(&b->theaplock);
    1175        3385 :                                         bi = bat_iterator_nolock(b);
    1176        3385 :                                         MT_lock_unset(&b->theaplock);
    1177        3385 :                                         bi.minpos = minpos;
    1178        3385 :                                         bi.maxpos = maxpos;
    1179        3385 :                                         vbase = b->tvheap->base;
    1180        3385 :                                         if (bi.minpos != BUN_NONE)
    1181        2635 :                                                 minvalp = BUNtvar(bi, bi.minpos);
    1182        3385 :                                         if (bi.maxpos != BUN_NONE)
    1183        2634 :                                                 maxvalp = BUNtvar(bi, bi.maxpos);
    1184             :                                 }
    1185    22042887 :                                 if (!isnil) {
    1186    20369058 :                                         if (p == 0) {
    1187      214948 :                                                 bi.minpos = bi.maxpos = 0;
    1188      214948 :                                                 minvalp = maxvalp = t;
    1189             :                                         } else {
    1190    39241005 :                                                 if (bi.minpos != BUN_NONE &&
    1191    19088284 :                                                     atomcmp(minvalp, t) > 0) {
    1192       82330 :                                                         bi.minpos = p;
    1193       82330 :                                                         minvalp = t;
    1194             :                                                 }
    1195    39238656 :                                                 if (bi.maxpos != BUN_NONE &&
    1196    19086579 :                                                     atomcmp(maxvalp, t) < 0) {
    1197     2246878 :                                                         bi.maxpos = p;
    1198     2246878 :                                                         maxvalp = t;
    1199             :                                                 }
    1200             :                                         }
    1201             :                                 } else {
    1202     1673829 :                                         b->tnil = true;
    1203     1673829 :                                         b->tnonil = false;
    1204             :                                 }
    1205    22040854 :                                 p++;
    1206             :                         }
    1207    22026234 :                         if (minbound)
    1208           0 :                                 VALclear(&minprop);
    1209    22026263 :                         if (maxbound)
    1210           0 :                                 VALclear(&maxprop);
    1211    22026134 :                         if (b->thash) {
    1212        5865 :                                 p -= count;
    1213       11730 :                                 for (BUN i = 0; i < count; i++) {
    1214        5865 :                                         t = ((void **) values)[i];
    1215        5865 :                                         HASHappend_locked(b, p, t);
    1216        5865 :                                         p++;
    1217             :                                 }
    1218        5865 :                                 nunique = b->thash ? b->thash->nunique : 0;
    1219             :                         }
    1220    32382978 :                 } else if (ATOMstorage(b->ttype) == TYPE_msk) {
    1221        7903 :                         bi.minpos = bi.maxpos = BUN_NONE;
    1222        7903 :                         minvalp = maxvalp = NULL;
    1223        7903 :                         b->tnil = false;
    1224        7903 :                         b->tnonil = true;
    1225       15806 :                         for (BUN i = 0; i < count; i++) {
    1226        7903 :                                 t = (void *) ((char *) values + (i << b->tshift));
    1227        7903 :                                 mskSetVal(b, p, *(msk *) t);
    1228        7903 :                                 p++;
    1229             :                         }
    1230             :                 } else {
    1231    32375075 :                         if (bi.minpos != BUN_NONE)
    1232    30800552 :                                 minvalp = BUNtloc(bi, bi.minpos);
    1233    32375075 :                         if (bi.maxpos != BUN_NONE)
    1234    30845562 :                                 maxvalp = BUNtloc(bi, bi.maxpos);
    1235    64787777 :                         for (BUN i = 0; i < count; i++) {
    1236    32424471 :                                 t = (void *) ((char *) values + (i << b->tshift));
    1237    32424471 :                                 gdk_return rc = tfastins_nocheckFIX(b, p, t);
    1238    32414082 :                                 if (rc != GDK_SUCCEED) {
    1239           0 :                                         MT_rwlock_wrunlock(&b->thashlock);
    1240           0 :                                         return rc;
    1241             :                                 }
    1242    32414082 :                                 if (b->thash) {
    1243      482561 :                                         HASHappend_locked(b, p, t);
    1244             :                                 }
    1245    32414082 :                                 if (atomcmp(t, atomnil) != 0) {
    1246    31351880 :                                         if (p == 0) {
    1247      377991 :                                                 bi.minpos = bi.maxpos = 0;
    1248      377991 :                                                 minvalp = maxvalp = t;
    1249             :                                         } else {
    1250    61797878 :                                                 if (bi.minpos != BUN_NONE &&
    1251    30824136 :                                                     atomcmp(minvalp, t) > 0) {
    1252       40624 :                                                         bi.minpos = p;
    1253       40624 :                                                         minvalp = t;
    1254             :                                                 }
    1255    61839556 :                                                 if (bi.maxpos != BUN_NONE &&
    1256    30868692 :                                                     atomcmp(maxvalp, t) < 0) {
    1257     7858522 :                                                         bi.maxpos = p;
    1258     7858522 :                                                         maxvalp = t;
    1259             :                                                 }
    1260             :                                         }
    1261             :                                 } else {
    1262     1063847 :                                         b->tnil = true;
    1263     1063847 :                                         b->tnonil = false;
    1264             :                                 }
    1265    32412702 :                                 p++;
    1266             :                         }
    1267    32363306 :                         nunique = b->thash ? b->thash->nunique : 0;
    1268             :                 }
    1269             :         } else {
    1270             :                 /* inserting nils, unless it's msk */
    1271       26753 :                 for (BUN i = 0; i < count; i++) {
    1272       15342 :                         gdk_return rc = tfastins_nocheck(b, p, t);
    1273       15340 :                         if (rc != GDK_SUCCEED) {
    1274           0 :                                 MT_rwlock_wrunlock(&b->thashlock);
    1275           0 :                                 return rc;
    1276             :                         }
    1277       15340 :                         if (b->thash) {
    1278           0 :                                 HASHappend_locked(b, p, t);
    1279             :                         }
    1280       15340 :                         p++;
    1281             :                 }
    1282       11411 :                 nunique = b->thash ? b->thash->nunique : 0;
    1283       11411 :                 b->tnil = b->ttype != TYPE_msk;
    1284       11411 :                 b->tnonil = false;
    1285             :         }
    1286    54408754 :         MT_lock_set(&b->theaplock);
    1287    54404525 :         b->tminpos = bi.minpos;
    1288    54404525 :         b->tmaxpos = bi.maxpos;
    1289    54404525 :         if (count > BATcount(b) / gdk_unique_estimate_keep_fraction)
    1290    17108544 :                 b->tunique_est = 0;
    1291             : 
    1292    54404525 :         if (b->ttype == TYPE_oid) {
    1293             :                 /* spend extra effort on oid (possible candidate list) */
    1294      565950 :                 if (values == NULL || is_oid_nil(((oid *) values)[0])) {
    1295         160 :                         b->tsorted = false;
    1296         160 :                         b->trevsorted = false;
    1297         160 :                         b->tkey = false;
    1298         160 :                         b->tseqbase = oid_nil;
    1299             :                 } else {
    1300      565790 :                         if (b->batCount == 0) {
    1301        6430 :                                 b->tsorted = true;
    1302        6430 :                                 b->trevsorted = true;
    1303        6430 :                                 b->tkey = true;
    1304        6430 :                                 b->tseqbase = count == 1 ? ((oid *) values)[0] : oid_nil;
    1305             :                         } else {
    1306      559360 :                                 if (!is_oid_nil(b->tseqbase) &&
    1307      320428 :                                     (count > 1 ||
    1308      320428 :                                      b->tseqbase + b->batCount != ((oid *) values)[0]))
    1309        2254 :                                         b->tseqbase = oid_nil;
    1310      559360 :                                 if (b->tsorted && !is_oid_nil(((oid *) b->theap->base)[b->batCount - 1]) && ((oid *) b->theap->base)[b->batCount - 1] > ((oid *) values)[0]) {
    1311          51 :                                         b->tsorted = false;
    1312          51 :                                         if (b->tnosorted == 0)
    1313          51 :                                                 b->tnosorted = b->batCount;
    1314             :                                 }
    1315      559360 :                                 if (b->trevsorted && !is_oid_nil(((oid *) values)[0]) && ((oid *) b->theap->base)[b->batCount - 1] < ((oid *) values)[0]) {
    1316        5623 :                                         b->trevsorted = false;
    1317        5623 :                                         if (b->tnorevsorted == 0)
    1318        5623 :                                                 b->tnorevsorted = b->batCount;
    1319             :                                 }
    1320      559360 :                                 if (b->tkey) {
    1321      557048 :                                         if (((oid *) b->theap->base)[b->batCount - 1] == ((oid *) values)[0]) {
    1322          17 :                                                 b->tkey = false;
    1323          17 :                                                 if (b->tnokey[1] == 0) {
    1324          17 :                                                         b->tnokey[0] = b->batCount - 1;
    1325          17 :                                                         b->tnokey[1] = b->batCount;
    1326             :                                                 }
    1327      557031 :                                         } else if (!b->tsorted && !b->trevsorted)
    1328          39 :                                                 b->tkey = false;
    1329             :                                 }
    1330             :                         }
    1331      565790 :                         for (BUN i = 1; i < count; i++) {
    1332           0 :                                 if (is_oid_nil(((oid *) values)[i])) {
    1333           0 :                                         b->tsorted = false;
    1334           0 :                                         b->trevsorted = false;
    1335           0 :                                         b->tkey = false;
    1336           0 :                                         b->tseqbase = oid_nil;
    1337           0 :                                         break;
    1338             :                                 }
    1339           0 :                                 if (((oid *) values)[i - 1] == ((oid *) values)[i]) {
    1340           0 :                                         b->tkey = false;
    1341           0 :                                         if (b->tnokey[1] == 0) {
    1342           0 :                                                 b->tnokey[0] = b->batCount + i - 1;
    1343           0 :                                                 b->tnokey[1] = b->batCount + i;
    1344             :                                         }
    1345           0 :                                 } else if (((oid *) values)[i - 1] > ((oid *) values)[i]) {
    1346           0 :                                         b->tsorted = false;
    1347           0 :                                         if (b->tnosorted == 0)
    1348           0 :                                                 b->tnosorted = b->batCount + i;
    1349           0 :                                         if (!b->trevsorted)
    1350           0 :                                                 b->tkey = false;
    1351             :                                 } else {
    1352           0 :                                         if (((oid *) values)[i - 1] + 1 != ((oid *) values)[i])
    1353           0 :                                                 b->tseqbase = oid_nil;
    1354           0 :                                         b->trevsorted = false;
    1355           0 :                                         if (b->tnorevsorted == 0)
    1356           0 :                                                 b->tnorevsorted = b->batCount + i;
    1357           0 :                                         if (!b->tsorted)
    1358           0 :                                                 b->tkey = false;
    1359             :                                 }
    1360             :                         }
    1361             :                 }
    1362    53838575 :         } else if (!ATOMlinear(b->ttype)) {
    1363        7903 :                 b->tsorted = b->trevsorted = b->tkey = false;
    1364    53830672 :         } else if (b->batCount == 0) {
    1365      598624 :                 if (values == NULL) {
    1366           0 :                         b->tsorted = b->trevsorted = true;
    1367           0 :                         b->tkey = count == 1;
    1368           0 :                         b->tunique_est = 1;
    1369             :                 } else {
    1370      598624 :                         int c;
    1371      598624 :                         switch (count) {
    1372      598303 :                         case 1:
    1373      598303 :                                 b->tsorted = b->trevsorted = b->tkey = true;
    1374      598303 :                                 b->tunique_est = 1;
    1375      598303 :                                 break;
    1376         122 :                         case 2:
    1377         122 :                                 if (b->tvheap)
    1378          41 :                                         c = ATOMcmp(b->ttype,
    1379             :                                                     ((void **) values)[0],
    1380             :                                                     ((void **) values)[1]);
    1381             :                                 else
    1382          81 :                                         c = ATOMcmp(b->ttype,
    1383             :                                                     values,
    1384             :                                                     (char *) values + b->twidth);
    1385         122 :                                 b->tsorted = c <= 0;
    1386         122 :                                 b->tnosorted = !b->tsorted;
    1387         122 :                                 b->trevsorted = c >= 0;
    1388         122 :                                 b->tnorevsorted = !b->trevsorted;
    1389         122 :                                 b->tkey = c != 0;
    1390         122 :                                 b->tnokey[0] = 0;
    1391         122 :                                 b->tnokey[1] = !b->tkey;
    1392         122 :                                 b->tunique_est = (double) (1 + b->tkey);
    1393         122 :                                 break;
    1394         199 :                         default:
    1395         199 :                                 b->tsorted = b->trevsorted = b->tkey = false;
    1396         199 :                                 break;
    1397             :                         }
    1398             :                 }
    1399    53232048 :         } else if (b->batCount == 1 && count == 1) {
    1400      432393 :                 bi = bat_iterator_nolock(b);
    1401      432393 :                 t = b->ttype == TYPE_msk ? &(msk){false} : ATOMnilptr(b->ttype);
    1402      432393 :                 if (values != NULL) {
    1403      432362 :                         if (b->tvheap)
    1404      163394 :                                 t = ((void **) values)[0];
    1405             :                         else
    1406             :                                 t = values;
    1407             :                 }
    1408      432393 :                 int c = ATOMcmp(b->ttype, BUNtail(bi, 0), t);
    1409      432266 :                 b->tsorted = c <= 0;
    1410      432266 :                 b->tnosorted = !b->tsorted;
    1411      432266 :                 b->trevsorted = c >= 0;
    1412      432266 :                 b->tnorevsorted = !b->trevsorted;
    1413      432266 :                 b->tkey = c != 0;
    1414      432266 :                 b->tnokey[0] = 0;
    1415      432266 :                 b->tnokey[1] = !b->tkey;
    1416      432266 :                 b->tunique_est = (double) (1 + b->tkey);
    1417             :         } else {
    1418    52799655 :                 b->tsorted = b->trevsorted = b->tkey = false;
    1419             :         }
    1420    54404398 :         BATsetcount(b, p);
    1421    54394863 :         if (nunique != 0)
    1422      488426 :                 b->tunique_est = (double) nunique;
    1423    54394863 :         MT_lock_unset(&b->theaplock);
    1424    54400104 :         MT_rwlock_wrunlock(&b->thashlock);
    1425             : 
    1426    54413454 :         OIDXdestroy(b);
    1427    54415051 :         STRMPdestroy(b);        /* TODO: use STRMPappendBitstring */
    1428    54415287 :         RTREEdestroy(b);
    1429    54415287 :         return GDK_SUCCEED;
    1430             : }
    1431             : 
    1432             : /* Append a single value to the bat. */
    1433             : gdk_return
    1434    39490509 : BUNappend(BAT *b, const void *t, bool force)
    1435             : {
    1436    39490509 :         return BUNappendmulti(b, b->ttype && b->tvheap ? (const void *) &t : (const void *) t, 1, force);
    1437             : }
    1438             : 
    1439             : gdk_return
    1440           4 : BUNdelete(BAT *b, oid o)
    1441             : {
    1442           4 :         BUN p;
    1443           4 :         BATiter bi = bat_iterator_nolock(b);
    1444           4 :         const void *val;
    1445           4 :         bool locked = false;
    1446           4 :         BUN nunique;
    1447             : 
    1448           4 :         assert(!is_oid_nil(b->hseqbase) || BATcount(b) == 0);
    1449           4 :         if (o < b->hseqbase || o >= b->hseqbase + BATcount(b)) {
    1450             :                 /* value already not there */
    1451             :                 return GDK_SUCCEED;
    1452             :         }
    1453           4 :         assert(BATcount(b) > 0); /* follows from "if" above */
    1454           4 :         p = o - b->hseqbase;
    1455           4 :         if (p < b->batInserted) {
    1456           0 :                 GDKerror("cannot delete committed value\n");
    1457           0 :                 return GDK_FAIL;
    1458             :         }
    1459           4 :         TRC_DEBUG(ALGO, ALGOBATFMT " deleting oid " OIDFMT "\n", ALGOBATPAR(b), o);
    1460             :         /* load hash so that we can maintain it */
    1461           4 :         (void) BATcheckhash(b);
    1462             : 
    1463           4 :         val = BUNtail(bi, p);
    1464             :         /* writing the values should be locked, reading could be done
    1465             :          * unlocked (since we're the only thread that should be changing
    1466             :          * anything) */
    1467           4 :         MT_lock_set(&b->theaplock);
    1468           4 :         if (b->tmaxpos == p)
    1469           1 :                 b->tmaxpos = BUN_NONE;
    1470           4 :         if (b->tminpos == p)
    1471           0 :                 b->tminpos = BUN_NONE;
    1472           4 :         MT_lock_unset(&b->theaplock);
    1473           4 :         nunique = HASHdelete(&bi, p, val);
    1474           4 :         ATOMdel(b->ttype, b->tvheap, (var_t *) BUNtloc(bi, p));
    1475           4 :         if (p != BATcount(b) - 1 &&
    1476           2 :             (b->ttype != TYPE_void || BATtdense(b))) {
    1477             :                 /* replace to-be-delete BUN with last BUN; materialize
    1478             :                  * void column before doing so */
    1479           2 :                 if (b->ttype == TYPE_void &&
    1480           0 :                     BATmaterialize(b, BUN_NONE) != GDK_SUCCEED)
    1481             :                         return GDK_FAIL;
    1482           2 :                 if (ATOMstorage(b->ttype) == TYPE_msk) {
    1483           0 :                         msk mval = mskGetVal(b, BATcount(b) - 1);
    1484           0 :                         assert(b->thash == NULL);
    1485           0 :                         mskSetVal(b, p, mval);
    1486             :                         /* don't leave garbage */
    1487           0 :                         mskClr(b, BATcount(b) - 1);
    1488             :                 } else {
    1489           2 :                         val = Tloc(b, BATcount(b) - 1);
    1490           2 :                         nunique = HASHdelete(&bi, BATcount(b) - 1, val);
    1491           2 :                         memcpy(Tloc(b, p), val, b->twidth);
    1492           2 :                         nunique = HASHinsert(&bi, p, val);
    1493           2 :                         MT_lock_set(&b->theaplock);
    1494           2 :                         locked = true;
    1495           2 :                         if (b->tminpos == BATcount(b) - 1)
    1496           0 :                                 b->tminpos = p;
    1497           2 :                         if (b->tmaxpos == BATcount(b) - 1)
    1498           1 :                                 b->tmaxpos = p;
    1499             :                 }
    1500             :                 /* no longer sorted */
    1501           2 :                 if (!locked) {
    1502           0 :                         MT_lock_set(&b->theaplock);
    1503           0 :                         locked = true;
    1504             :                 }
    1505           2 :                 b->tsorted = b->trevsorted = false;
    1506           2 :                 b->theap->dirty = true;
    1507             :         }
    1508           4 :         if (!locked)
    1509           2 :                 MT_lock_set(&b->theaplock);
    1510           4 :         if (b->tnosorted >= p)
    1511           0 :                 b->tnosorted = 0;
    1512           4 :         if (b->tnorevsorted >= p)
    1513           1 :                 b->tnorevsorted = 0;
    1514           4 :         b->batCount--;
    1515           4 :         if (nunique != 0)
    1516           0 :                 b->tunique_est = (double) nunique;
    1517           4 :         else if (BATcount(b) < gdk_unique_estimate_keep_fraction)
    1518           4 :                 b->tunique_est = 0;
    1519           4 :         if (b->batCount <= 1) {
    1520             :                 /* some trivial properties */
    1521           0 :                 b->tkey = true;
    1522           0 :                 b->tsorted = b->trevsorted = true;
    1523           0 :                 b->tnosorted = b->tnorevsorted = 0;
    1524           0 :                 if (b->batCount == 0) {
    1525           0 :                         b->tnil = false;
    1526           0 :                         b->tnonil = true;
    1527             :                 }
    1528             :         }
    1529           4 :         MT_lock_unset(&b->theaplock);
    1530           4 :         OIDXdestroy(b);
    1531           4 :         return GDK_SUCCEED;
    1532             : }
    1533             : 
    1534             : /* @-  BUN replace
    1535             :  * The last operation in this context is BUN replace. It assumes that
    1536             :  * the header denotes a key. The old value association is destroyed
    1537             :  * (if it exists in the first place) and the new value takes its
    1538             :  * place.
    1539             :  *
    1540             :  * In order to make updates on void columns workable; replaces on them
    1541             :  * are always done in-place. Performing them without bun-movements
    1542             :  * greatly simplifies the problem. The 'downside' is that when
    1543             :  * transaction management has to be performed, replaced values should
    1544             :  * be saved explicitly.
    1545             :  */
    1546             : static gdk_return
    1547     1099416 : BUNinplacemulti(BAT *b, const oid *positions, const void *values, BUN count, bool force, bool autoincr)
    1548             : {
    1549     1099416 :         BUN prv, nxt;
    1550     1099416 :         const void *val;
    1551     1099416 :         int (*atomcmp) (const void *, const void *) = ATOMcompare(b->ttype);
    1552     1099416 :         const void *atomnil = ATOMnilptr(b->ttype);
    1553             : 
    1554     1099416 :         MT_lock_set(&b->theaplock);
    1555     1099479 :         BUN last = BATcount(b) - 1;
    1556     1099479 :         BATiter bi = bat_iterator_nolock(b);
    1557             :         /* zap alignment info */
    1558     1099479 :         if (!force && (b->batRestricted != BAT_WRITE ||
    1559      551787 :                        ((ATOMIC_GET(&b->theap->refs) & HEAPREFS) > 1))) {
    1560           0 :                 MT_lock_unset(&b->theaplock);
    1561           0 :                 GDKerror("access denied to %s, aborting.\n",
    1562             :                          BATgetId(b));
    1563           0 :                 assert(0);
    1564             :                 return GDK_FAIL;
    1565             :         }
    1566     1099479 :         TRC_DEBUG(ALGO, ALGOBATFMT " replacing " BUNFMT " values\n", ALGOBATPAR(b), count);
    1567     1099378 :         if (b->ttype == TYPE_void) {
    1568           0 :                 PROPdestroy(b);
    1569           0 :                 b->tminpos = BUN_NONE;
    1570           0 :                 b->tmaxpos = BUN_NONE;
    1571           0 :                 b->tunique_est = 0.0;
    1572     1099378 :         } else if (count > BATcount(b) / gdk_unique_estimate_keep_fraction) {
    1573      541462 :                 b->tunique_est = 0;
    1574             :         }
    1575     1099378 :         const ValRecord *prop;
    1576     1099378 :         ValRecord minprop, maxprop;
    1577     1099378 :         const void *minbound = NULL, *maxbound = NULL;
    1578     1099378 :         if ((prop = BATgetprop_nolock(b, GDK_MIN_BOUND)) != NULL &&
    1579           0 :             VALcopy(&minprop, prop) != NULL)
    1580           0 :                 minbound = VALptr(&minprop);
    1581     1099374 :         if ((prop = BATgetprop_nolock(b, GDK_MAX_BOUND)) != NULL &&
    1582           0 :             VALcopy(&maxprop, prop) != NULL)
    1583           0 :                 maxbound = VALptr(&maxprop);
    1584     1099323 :         const bool notnull = BATgetprop_nolock(b, GDK_NOT_NULL) != NULL;
    1585     1099002 :         MT_lock_unset(&b->theaplock);
    1586             :         /* load hash so that we can maintain it */
    1587     1098878 :         (void) BATcheckhash(b);
    1588     1099288 :         MT_rwlock_wrlock(&b->thashlock);
    1589     2198565 :         for (BUN i = 0; i < count; i++) {
    1590     1099419 :                 BUN p = autoincr ? positions[0] - b->hseqbase + i : positions[i] - b->hseqbase;
    1591     1099478 :                 const void *t = b->ttype && b->tvheap ?
    1592     1252069 :                         ((const void **) values)[i] :
    1593      946769 :                         (const void *) ((const char *) values + (i << b->tshift));
    1594     1099419 :                 bool isnil = atomnil && atomcmp(t, atomnil) == 0;
    1595     1099259 :                 if (notnull && isnil) {
    1596           0 :                         assert(0);
    1597             :                         GDKerror("NULL value not within bounds\n");
    1598             :                         MT_rwlock_wrunlock(&b->thashlock);
    1599             :                         goto bailout;
    1600     1099259 :                 } else if (!isnil &&
    1601          76 :                            ((minbound &&
    1602     1051278 :                              atomcmp(t, minbound) < 0) ||
    1603           0 :                             (maxbound &&
    1604           0 :                              atomcmp(t, maxbound) >= 0))) {
    1605           0 :                         assert(0);
    1606             :                         GDKerror("value not within bounds\n");
    1607             :                         MT_rwlock_wrunlock(&b->thashlock);
    1608             :                         goto bailout;
    1609             :                 }
    1610             : 
    1611             :                 /* retrieve old value, but if this comes from the
    1612             :                  * logger, we need to deal with offsets that point
    1613             :                  * outside of the valid vheap */
    1614     1099335 :                 if (b->ttype == TYPE_void) {
    1615           0 :                         val = BUNtpos(bi, p);
    1616     1099335 :                 } else if (bi.type == TYPE_msk) {
    1617         118 :                         val = BUNtmsk(bi, p);
    1618     1099217 :                 } else if (b->tvheap) {
    1619      152622 :                         size_t off = BUNtvaroff(bi, p);
    1620      152622 :                         if (off < bi.vhfree)
    1621      152629 :                                 val = bi.vh->base + off;
    1622             :                         else
    1623             :                                 val = NULL; /* bad offset */
    1624             :                 } else {
    1625      946595 :                         val = BUNtloc(bi, p);
    1626             :                 }
    1627             : 
    1628     1099342 :                 if (val) {
    1629     1099342 :                         if (atomcmp(val, t) == 0)
    1630      258066 :                                 continue; /* nothing to do */
    1631      841235 :                         if (!isnil &&
    1632      167970 :                             b->tnil &&
    1633      167970 :                             atomcmp(val, atomnil) == 0) {
    1634             :                                 /* if old value is nil and new value
    1635             :                                  * isn't, we're not sure anymore about
    1636             :                                  * the nil property, so we must clear
    1637             :                                  * it */
    1638      167811 :                                 MT_lock_set(&b->theaplock);
    1639      167810 :                                 b->tnil = false;
    1640      167810 :                                 MT_lock_unset(&b->theaplock);
    1641             :                         }
    1642      841234 :                         if (b->ttype != TYPE_void) {
    1643      841240 :                                 if (bi.maxpos != BUN_NONE) {
    1644      523389 :                                         if (!isnil && atomcmp(BUNtail(bi, bi.maxpos), t) < 0) {
    1645             :                                                 /* new value is larger
    1646             :                                                  * than previous
    1647             :                                                  * largest */
    1648       54901 :                                                 bi.maxpos = p;
    1649      468489 :                                         } else if (bi.maxpos == p && atomcmp(BUNtail(bi, bi.maxpos), t) != 0) {
    1650             :                                                 /* old value is equal to
    1651             :                                                  * largest and new value
    1652             :                                                  * is smaller or nil (see
    1653             :                                                  * above), so we don't
    1654             :                                                  * know anymore which is
    1655             :                                                  * the largest */
    1656         498 :                                                 bi.maxpos = BUN_NONE;
    1657             :                                         }
    1658             :                                 }
    1659      841241 :                                 if (bi.minpos != BUN_NONE) {
    1660      371732 :                                         if (!isnil && atomcmp(BUNtail(bi, bi.minpos), t) > 0) {
    1661             :                                                 /* new value is smaller
    1662             :                                                  * than previous
    1663             :                                                  * smallest */
    1664         426 :                                                 bi.minpos = p;
    1665      371305 :                                         } else if (bi.minpos == p && atomcmp(BUNtail(bi, bi.minpos), t) != 0) {
    1666             :                                                 /* old value is equal to
    1667             :                                                  * smallest and new value
    1668             :                                                  * is larger or nil (see
    1669             :                                                  * above), so we don't
    1670             :                                                  * know anymore which is
    1671             :                                                  * the largest */
    1672         626 :                                                 bi.minpos = BUN_NONE;
    1673             :                                         }
    1674             :                                 }
    1675             :                         }
    1676      841234 :                         HASHdelete_locked(&bi, p, val);     /* first delete old value from hash */
    1677             :                 } else {
    1678             :                         /* out of range old value, so the properties and
    1679             :                          * hash cannot be trusted */
    1680           0 :                         PROPdestroy(b);
    1681           0 :                         Hash *hs = b->thash;
    1682           0 :                         if (hs) {
    1683           0 :                                 b->thash = NULL;
    1684           0 :                                 doHASHdestroy(b, hs);
    1685             :                         }
    1686           0 :                         MT_lock_set(&b->theaplock);
    1687           0 :                         bi.minpos = BUN_NONE;
    1688           0 :                         bi.maxpos = BUN_NONE;
    1689           0 :                         b->tunique_est = 0.0;
    1690           0 :                         MT_lock_unset(&b->theaplock);
    1691             :                 }
    1692      841268 :                 OIDXdestroy(b);
    1693      841288 :                 STRMPdestroy(b);
    1694      841276 :                 RTREEdestroy(b);
    1695             : 
    1696      841323 :                 if (b->tvheap && b->ttype) {
    1697       75118 :                         var_t _d;
    1698       75118 :                         ptr _ptr;
    1699       75118 :                         _ptr = BUNtloc(bi, p);
    1700       75118 :                         switch (b->twidth) {
    1701        8755 :                         case 1:
    1702        8755 :                                 _d = (var_t) * (uint8_t *) _ptr + GDK_VAROFFSET;
    1703        8755 :                                 break;
    1704       60405 :                         case 2:
    1705       60405 :                                 _d = (var_t) * (uint16_t *) _ptr + GDK_VAROFFSET;
    1706       60405 :                                 break;
    1707        5958 :                         case 4:
    1708        5958 :                                 _d = (var_t) * (uint32_t *) _ptr;
    1709        5958 :                                 break;
    1710             : #if SIZEOF_VAR_T == 8
    1711           0 :                         case 8:
    1712           0 :                                 _d = (var_t) * (uint64_t *) _ptr;
    1713           0 :                                 break;
    1714             : #endif
    1715             :                         default:
    1716           0 :                                 MT_UNREACHABLE();
    1717             :                         }
    1718       75118 :                         MT_lock_set(&b->theaplock);
    1719       75116 :                         if (ATOMreplaceVAR(b, &_d, t) != GDK_SUCCEED) {
    1720           0 :                                 MT_lock_unset(&b->theaplock);
    1721           0 :                                 MT_rwlock_wrunlock(&b->thashlock);
    1722           0 :                                 goto bailout;
    1723             :                         }
    1724       75127 :                         MT_lock_unset(&b->theaplock);
    1725       75134 :                         if (b->twidth < SIZEOF_VAR_T &&
    1726       75134 :                             (b->twidth <= 2 ? _d - GDK_VAROFFSET : _d) >= ((size_t) 1 << (8 << b->tshift))) {
    1727             :                                 /* doesn't fit in current heap, upgrade it */
    1728          84 :                                 if (GDKupgradevarheap(b, _d, 0, bi.count) != GDK_SUCCEED) {
    1729           0 :                                         MT_rwlock_wrunlock(&b->thashlock);
    1730           0 :                                         goto bailout;
    1731             :                                 }
    1732             :                         }
    1733             :                         /* reinitialize iterator after possible heap upgrade */
    1734             :                         {
    1735             :                                 /* save and restore minpos/maxpos */
    1736       75134 :                                 BUN minpos = bi.minpos;
    1737       75134 :                                 BUN maxpos = bi.maxpos;
    1738       75134 :                                 bi = bat_iterator_nolock(b);
    1739       75134 :                                 bi.minpos = minpos;
    1740       75134 :                                 bi.maxpos = maxpos;
    1741             :                         }
    1742       75134 :                         _ptr = BUNtloc(bi, p);
    1743       75134 :                         switch (b->twidth) {
    1744        8680 :                         case 1:
    1745        8680 :                                 * (uint8_t *) _ptr = (uint8_t) (_d - GDK_VAROFFSET);
    1746        8680 :                                 break;
    1747       60487 :                         case 2:
    1748       60487 :                                 * (uint16_t *) _ptr = (uint16_t) (_d - GDK_VAROFFSET);
    1749       60487 :                                 break;
    1750        5967 :                         case 4:
    1751        5967 :                                 * (uint32_t *) _ptr = (uint32_t) _d;
    1752        5967 :                                 break;
    1753             : #if SIZEOF_VAR_T == 8
    1754           0 :                         case 8:
    1755           0 :                                 * (uint64_t *) _ptr = (uint64_t) _d;
    1756           0 :                                 break;
    1757             : #endif
    1758             :                         default:
    1759       75134 :                                 MT_UNREACHABLE();
    1760             :                         }
    1761      766205 :                 } else if (ATOMstorage(b->ttype) == TYPE_msk) {
    1762         118 :                         mskSetVal(b, p, * (msk *) t);
    1763             :                 } else {
    1764      766087 :                         assert(BATatoms[b->ttype].atomPut == NULL);
    1765      766087 :                         switch (ATOMsize(b->ttype)) {
    1766             :                         case 0:      /* void */
    1767             :                                 break;
    1768       15415 :                         case 1:
    1769       15415 :                                 ((bte *) b->theap->base)[p] = * (bte *) t;
    1770       15415 :                                 break;
    1771        6933 :                         case 2:
    1772        6933 :                                 ((sht *) b->theap->base)[p] = * (sht *) t;
    1773        6933 :                                 break;
    1774      191201 :                         case 4:
    1775      191201 :                                 ((int *) b->theap->base)[p] = * (int *) t;
    1776      191201 :                                 break;
    1777      552538 :                         case 8:
    1778      552538 :                                 ((lng *) b->theap->base)[p] = * (lng *) t;
    1779      552538 :                                 break;
    1780           0 :                         case 16:
    1781             : #ifdef HAVE_HGE
    1782           0 :                                 ((hge *) b->theap->base)[p] = * (hge *) t;
    1783             : #else
    1784             :                                 ((uuid *) b->theap->base)[p] = * (uuid *) t;
    1785             : #endif
    1786           0 :                                 break;
    1787           0 :                         default:
    1788           0 :                                 memcpy(BUNtloc(bi, p), t, ATOMsize(b->ttype));
    1789           0 :                                 break;
    1790             :                         }
    1791             :                 }
    1792             : 
    1793      841339 :                 HASHinsert_locked(&bi, p, t);       /* insert new value into hash */
    1794             : 
    1795      841284 :                 prv = p > 0 ? p - 1 : BUN_NONE;
    1796      841284 :                 nxt = p < last ? p + 1 : BUN_NONE;
    1797             : 
    1798      841284 :                 MT_lock_set(&b->theaplock);
    1799      841252 :                 if (b->tsorted) {
    1800        2935 :                         if (prv != BUN_NONE &&
    1801        1156 :                             atomcmp(t, BUNtail(bi, prv)) < 0) {
    1802          31 :                                 b->tsorted = false;
    1803          31 :                                 b->tnosorted = p;
    1804        2472 :                         } else if (nxt != BUN_NONE &&
    1805         724 :                                    atomcmp(t, BUNtail(bi, nxt)) > 0) {
    1806         649 :                                 b->tsorted = false;
    1807         649 :                                 b->tnosorted = nxt;
    1808        1099 :                         } else if (b->ttype != TYPE_void && BATtdense(b)) {
    1809           0 :                                 if (prv != BUN_NONE &&
    1810           0 :                                     1 + * (oid *) BUNtloc(bi, prv) != * (oid *) t) {
    1811           0 :                                         b->tseqbase = oid_nil;
    1812           0 :                                 } else if (nxt != BUN_NONE &&
    1813           0 :                                            * (oid *) BUNtloc(bi, nxt) != 1 + * (oid *) t) {
    1814           0 :                                         b->tseqbase = oid_nil;
    1815           0 :                                 } else if (prv == BUN_NONE &&
    1816           0 :                                            nxt == BUN_NONE) {
    1817           0 :                                         b->tseqbase = * (oid *) t;
    1818             :                                 }
    1819             :                         }
    1820      839473 :                 } else if (b->tnosorted >= p)
    1821        3630 :                         b->tnosorted = 0;
    1822      841252 :                 if (b->trevsorted) {
    1823        1432 :                         if (prv != BUN_NONE &&
    1824         433 :                             atomcmp(t, BUNtail(bi, prv)) > 0) {
    1825          54 :                                 b->trevsorted = false;
    1826          54 :                                 b->tnorevsorted = p;
    1827        1102 :                         } else if (nxt != BUN_NONE &&
    1828         157 :                                    atomcmp(t, BUNtail(bi, nxt)) < 0) {
    1829          33 :                                 b->trevsorted = false;
    1830          33 :                                 b->tnorevsorted = nxt;
    1831             :                         }
    1832      840253 :                 } else if (b->tnorevsorted >= p)
    1833        2014 :                         b->tnorevsorted = 0;
    1834      841252 :                 if (((b->ttype != TYPE_void) & b->tkey) && b->batCount > 1) {
    1835         938 :                         BATkey(b, false);
    1836      840314 :                 } else if (!b->tkey && (b->tnokey[0] == p || b->tnokey[1] == p))
    1837         883 :                         b->tnokey[0] = b->tnokey[1] = 0;
    1838      841252 :                 if (b->tnonil && ATOMstorage(b->ttype) != TYPE_msk)
    1839      607774 :                         b->tnonil = t && atomcmp(t, atomnil) != 0;
    1840     1099326 :                 MT_lock_unset(&b->theaplock);
    1841             :         }
    1842     1099270 :         BUN nunique = b->thash ? b->thash->nunique : 0;
    1843     1099270 :         MT_rwlock_wrunlock(&b->thashlock);
    1844     1099278 :         MT_lock_set(&b->theaplock);
    1845     1098663 :         if (nunique != 0)
    1846       26611 :                 b->tunique_est = (double) nunique;
    1847     1098663 :         b->tminpos = bi.minpos;
    1848     1098663 :         b->tmaxpos = bi.maxpos;
    1849     1098663 :         b->theap->dirty = true;
    1850     1098663 :         if (b->tvheap)
    1851      152529 :                 b->tvheap->dirty = true;
    1852     1098663 :         MT_lock_unset(&b->theaplock);
    1853             : 
    1854     1098364 :         return GDK_SUCCEED;
    1855             : 
    1856           0 :   bailout:
    1857           0 :         if (minbound)
    1858           0 :                 VALclear(&minprop);
    1859           0 :         if (maxbound)
    1860           0 :                 VALclear(&maxprop);
    1861             :         return GDK_FAIL;
    1862             : }
    1863             : 
    1864             : /* Replace multiple values given by their positions with the given values. */
    1865             : gdk_return
    1866      555393 : BUNreplacemulti(BAT *b, const oid *positions, const void *values, BUN count, bool force)
    1867             : {
    1868      555393 :         BATcheck(b, GDK_FAIL);
    1869             : 
    1870      555393 :         if (b->ttype == TYPE_void && BATmaterialize(b, BUN_NONE) != GDK_SUCCEED)
    1871             :                 return GDK_FAIL;
    1872             : 
    1873      555393 :         return BUNinplacemulti(b, positions, values, count, force, false);
    1874             : }
    1875             : 
    1876             : /* Replace multiple values starting from a given position with the given
    1877             :  * values. */
    1878             : gdk_return
    1879      540353 : BUNreplacemultiincr(BAT *b, oid position, const void *values, BUN count, bool force)
    1880             : {
    1881      540353 :         BATcheck(b, GDK_FAIL);
    1882             : 
    1883      540353 :         if (b->ttype == TYPE_void && BATmaterialize(b, BUN_NONE) != GDK_SUCCEED)
    1884             :                 return GDK_FAIL;
    1885             : 
    1886      540353 :         return BUNinplacemulti(b, &position, values, count, force, true);
    1887             : }
    1888             : 
    1889             : gdk_return
    1890      555393 : BUNreplace(BAT *b, oid id, const void *t, bool force)
    1891             : {
    1892      555393 :         return BUNreplacemulti(b, &id, b->ttype && b->tvheap ? (const void *) &t : t, 1, force);
    1893             : }
    1894             : 
    1895             : /* very much like BUNreplace, but this doesn't make any changes if the
    1896             :  * tail column is void */
    1897             : gdk_return
    1898        3639 : void_inplace(BAT *b, oid id, const void *val, bool force)
    1899             : {
    1900        3639 :         assert(id >= b->hseqbase && id < b->hseqbase + BATcount(b));
    1901        3639 :         if (id < b->hseqbase || id >= b->hseqbase + BATcount(b)) {
    1902             :                 GDKerror("id out of range\n");
    1903             :                 return GDK_FAIL;
    1904             :         }
    1905        3639 :         if (b->ttype == TYPE_void)
    1906             :                 return GDK_SUCCEED;
    1907        3639 :         return BUNinplacemulti(b, &id, b->ttype && b->tvheap ? (const void *) &val : (const void *) val, 1, force, false);
    1908             : }
    1909             : 
    1910             : /*
    1911             :  * @- BUN Lookup
    1912             :  * Location of a BUN using a value should use the available indexes to
    1913             :  * speed up access. If indexes are lacking then a hash index is
    1914             :  * constructed under the assumption that 1) multiple access to the BAT
    1915             :  * can be expected and 2) building the hash is only slightly more
    1916             :  * expensive than the full linear scan.  BUN_NONE is returned if no
    1917             :  * such element could be found.  In those cases where the type is
    1918             :  * known and a hash index is available, one should use the inline
    1919             :  * functions to speed-up processing.
    1920             :  */
    1921             : static BUN
    1922           0 : slowfnd(BAT *b, const void *v)
    1923             : {
    1924           0 :         BATiter bi = bat_iterator(b);
    1925           0 :         BUN p, q;
    1926           0 :         int (*cmp)(const void *, const void *) = ATOMcompare(bi.type);
    1927             : 
    1928           0 :         BATloop(b, p, q) {
    1929           0 :                 if ((*cmp)(v, BUNtail(bi, p)) == 0) {
    1930           0 :                         bat_iterator_end(&bi);
    1931           0 :                         return p;
    1932             :                 }
    1933             :         }
    1934           0 :         bat_iterator_end(&bi);
    1935           0 :         return BUN_NONE;
    1936             : }
    1937             : 
    1938             : static BUN
    1939           0 : mskfnd(BAT *b, msk v)
    1940             : {
    1941           0 :         BUN p, q;
    1942             : 
    1943           0 :         if (v) {
    1944             :                 /* find a 1 value */
    1945           0 :                 for (p = 0, q = (BATcount(b) + 31) / 32; p < q; p++) {
    1946           0 :                         if (((uint32_t *) b->theap->base)[p] != 0) {
    1947             :                                 /* there's at least one 1 bit */
    1948           0 :                                 return p * 32 + candmask_lobit(((uint32_t *) b->theap->base)[p]);
    1949             :                         }
    1950             :                 }
    1951             :         } else {
    1952             :                 /* find a 0 value */
    1953           0 :                 for (p = 0, q = (BATcount(b) + 31) / 32; p < q; p++) {
    1954           0 :                         if (((uint32_t *) b->theap->base)[p] != ~0U) {
    1955             :                                 /* there's at least one 0 bit */
    1956           0 :                                 return p * 32 + candmask_lobit(~((uint32_t *) b->theap->base)[p]);
    1957             :                         }
    1958             :                 }
    1959             :         }
    1960             :         return BUN_NONE;
    1961             : }
    1962             : 
    1963             : BUN
    1964     1784724 : BUNfnd(BAT *b, const void *v)
    1965             : {
    1966     1784724 :         BUN r = BUN_NONE;
    1967     1784724 :         BATiter bi;
    1968             : 
    1969     1784724 :         BATcheck(b, BUN_NONE);
    1970     1784724 :         if (!v || BATcount(b) == 0)
    1971             :                 return r;
    1972     1371460 :         if (complex_cand(b)) {
    1973           0 :                 struct canditer ci;
    1974           0 :                 canditer_init(&ci, NULL, b);
    1975           0 :                 return canditer_search(&ci, * (const oid *) v, false);
    1976             :         }
    1977     1371460 :         if (BATtvoid(b))
    1978      727168 :                 return BUNfndVOID(b, v);
    1979      644292 :         if (ATOMstorage(b->ttype) == TYPE_msk) {
    1980           0 :                 return mskfnd(b, *(msk*)v);
    1981             :         }
    1982      644292 :         if (!BATcheckhash(b)) {
    1983      168427 :                 if (BATordered(b) || BATordered_rev(b))
    1984      168089 :                         return SORTfnd(b, v);
    1985             :         }
    1986      476193 :         if (BAThash(b) == GDK_SUCCEED) {
    1987      476213 :                 bi = bat_iterator(b); /* outside of hashlock */
    1988      476217 :                 MT_rwlock_rdlock(&b->thashlock);
    1989      476217 :                 if (b->thash == NULL) {
    1990           0 :                         MT_rwlock_rdunlock(&b->thashlock);
    1991           0 :                         bat_iterator_end(&bi);
    1992           0 :                         goto hashfnd_failed;
    1993             :                 }
    1994      952196 :                 switch (ATOMbasetype(bi.type)) {
    1995           5 :                 case TYPE_bte:
    1996           5 :                         HASHloop_bte(bi, b->thash, r, v)
    1997             :                                 break;
    1998             :                         break;
    1999           0 :                 case TYPE_sht:
    2000           0 :                         HASHloop_sht(bi, b->thash, r, v)
    2001             :                                 break;
    2002             :                         break;
    2003          32 :                 case TYPE_int:
    2004          32 :                         HASHloop_int(bi, b->thash, r, v)
    2005             :                                 break;
    2006             :                         break;
    2007           0 :                 case TYPE_flt:
    2008           0 :                         HASHloop_flt(bi, b->thash, r, v)
    2009             :                                 break;
    2010             :                         break;
    2011           0 :                 case TYPE_dbl:
    2012           0 :                         HASHloop_dbl(bi, b->thash, r, v)
    2013             :                                 break;
    2014             :                         break;
    2015         221 :                 case TYPE_lng:
    2016         221 :                         HASHloop_lng(bi, b->thash, r, v)
    2017             :                                 break;
    2018             :                         break;
    2019             : #ifdef HAVE_HGE
    2020           0 :                 case TYPE_hge:
    2021           0 :                         HASHloop_hge(bi, b->thash, r, v)
    2022             :                                 break;
    2023             :                         break;
    2024             : #endif
    2025           0 :                 case TYPE_uuid:
    2026           0 :                         HASHloop_uuid(bi, b->thash, r, v)
    2027             :                                 break;
    2028             :                         break;
    2029      475958 :                 case TYPE_str:
    2030      660680 :                         HASHloop_str(bi, b->thash, r, v)
    2031             :                                 break;
    2032             :                         break;
    2033           1 :                 default:
    2034           3 :                         HASHloop(bi, b->thash, r, v)
    2035             :                                 break;
    2036             :                         break;
    2037             :                 }
    2038      476217 :                 MT_rwlock_rdunlock(&b->thashlock);
    2039      476215 :                 bat_iterator_end(&bi);
    2040      476215 :                 return r;
    2041             :         }
    2042           0 :   hashfnd_failed:
    2043             :         /* can't build hash table, search the slow way */
    2044           0 :         GDKclrerr();
    2045           0 :         return slowfnd(b, v);
    2046             : }
    2047             : 
    2048             : /*
    2049             :  * @+ BAT Property Management
    2050             :  *
    2051             :  * The function BATcount returns the number of active elements in a
    2052             :  * BAT.  Counting is type independent.  It can be implemented quickly,
    2053             :  * because the system ensures a dense BUN list.
    2054             :  */
    2055             : void
    2056     1933847 : BATsetcapacity(BAT *b, BUN cnt)
    2057             : {
    2058     1933847 :         b->batCapacity = cnt;
    2059     1933847 :         assert(b->batCount <= cnt);
    2060     1933847 : }
    2061             : 
    2062             : /* Set the batCount value for the bat and also set some dependent
    2063             :  * properties.  This function should be called only when it is save from
    2064             :  * concurrent use (e.g. when theaplock is being held). */
    2065             : void
    2066    74217708 : BATsetcount(BAT *b, BUN cnt)
    2067             : {
    2068             :         /* head column is always VOID, and some head properties never change */
    2069    74217708 :         assert(!is_oid_nil(b->hseqbase));
    2070    74217708 :         assert(cnt <= BUN_MAX);
    2071             : 
    2072    74217708 :         b->batCount = cnt;
    2073    74217708 :         if (b->theap->parentid == b->batCacheid) {
    2074    72291867 :                 b->theap->dirty |= b->ttype != TYPE_void && cnt > 0;
    2075    72291867 :                 b->theap->free = tailsize(b, cnt);
    2076             :         }
    2077    74217708 :         if (b->ttype == TYPE_void)
    2078     9507155 :                 b->batCapacity = cnt;
    2079    74217708 :         if (cnt <= 1) {
    2080    13876946 :                 b->tsorted = b->trevsorted = ATOMlinear(b->ttype);
    2081    13876946 :                 b->tnosorted = b->tnorevsorted = 0;
    2082             :         }
    2083             :         /* if the BAT was made smaller, we need to zap some values */
    2084    74217708 :         if (b->tnosorted >= BATcount(b))
    2085    12074035 :                 b->tnosorted = 0;
    2086    74217708 :         if (b->tnorevsorted >= BATcount(b))
    2087    11997289 :                 b->tnorevsorted = 0;
    2088    74217708 :         if (b->tnokey[0] >= BATcount(b) || b->tnokey[1] >= BATcount(b)) {
    2089    12043862 :                 b->tnokey[0] = 0;
    2090    12043862 :                 b->tnokey[1] = 0;
    2091             :         }
    2092    74217708 :         if (b->ttype == TYPE_void) {
    2093     9507386 :                 b->tsorted = true;
    2094     9507386 :                 if (is_oid_nil(b->tseqbase)) {
    2095     4906757 :                         b->tkey = cnt <= 1;
    2096     4906757 :                         b->trevsorted = true;
    2097     4906757 :                         b->tnil = true;
    2098     4906757 :                         b->tnonil = false;
    2099             :                 } else {
    2100     4600629 :                         b->tkey = true;
    2101     4600629 :                         b->trevsorted = cnt <= 1;
    2102     4600629 :                         b->tnil = false;
    2103     4600629 :                         b->tnonil = true;
    2104             :                 }
    2105             :         }
    2106    74217708 :         assert(b->batCapacity >= cnt);
    2107    74217708 : }
    2108             : 
    2109             : /*
    2110             :  * The key and name properties can be changed at any time.  Keyed
    2111             :  * dimensions are automatically supported by an auxiliary hash-based
    2112             :  * access structure to speed up searching. Turning off the key
    2113             :  * integrity property does not cause the index to disappear. It can
    2114             :  * still be used to speed-up retrieval. The routine BATkey sets the
    2115             :  * key property of the association head.
    2116             :  */
    2117             : gdk_return
    2118       47345 : BATkey(BAT *b, bool flag)
    2119             : {
    2120       47345 :         BATcheck(b, GDK_FAIL);
    2121       47345 :         if (b->ttype == TYPE_void) {
    2122        1112 :                 if (BATtdense(b) && !flag) {
    2123           0 :                         GDKerror("dense column must be unique.\n");
    2124           0 :                         return GDK_FAIL;
    2125             :                 }
    2126        1112 :                 if (is_oid_nil(b->tseqbase) && flag && b->batCount > 1) {
    2127           0 :                         GDKerror("void column cannot be unique.\n");
    2128           0 :                         return GDK_FAIL;
    2129             :                 }
    2130             :         }
    2131       47345 :         b->tkey = flag;
    2132       47345 :         if (!flag) {
    2133       32426 :                 b->tseqbase = oid_nil;
    2134             :         } else
    2135       14919 :                 b->tnokey[0] = b->tnokey[1] = 0;
    2136       47345 :         gdk_return rc = GDK_SUCCEED;
    2137       47345 :         if (flag && VIEWtparent(b)) {
    2138             :                 /* if a view is key, then so is the parent if the two
    2139             :                  * are aligned */
    2140           2 :                 BAT *bp = BATdescriptor(VIEWtparent(b));
    2141           2 :                 if (bp != NULL) {
    2142           2 :                         MT_lock_set(&bp->theaplock);
    2143           4 :                         if (BATcount(b) == BATcount(bp) &&
    2144           2 :                             ATOMtype(BATttype(b)) == ATOMtype(BATttype(bp)) &&
    2145           2 :                             !BATtkey(bp) &&
    2146           0 :                             ((BATtvoid(b) && BATtvoid(bp) && b->tseqbase == bp->tseqbase) ||
    2147             :                              BATcount(b) == 0))
    2148           0 :                                 rc = BATkey(bp, true);
    2149           2 :                         MT_lock_unset(&bp->theaplock);
    2150           2 :                         BBPunfix(bp->batCacheid);
    2151             :                 }
    2152             :         }
    2153             :         return rc;
    2154             : }
    2155             : 
    2156             : void
    2157     1698858 : BAThseqbase(BAT *b, oid o)
    2158             : {
    2159     1698858 :         if (b != NULL) {
    2160     1698858 :                 assert(o <= GDK_oid_max);    /* i.e., not oid_nil */
    2161     1698858 :                 assert(o + BATcount(b) <= GDK_oid_max);
    2162     1698858 :                 b->hseqbase = o;
    2163             :         }
    2164     1698858 : }
    2165             : 
    2166             : void
    2167     5501114 : BATtseqbase(BAT *b, oid o)
    2168             : {
    2169     5501114 :         assert(o <= oid_nil);
    2170     5501114 :         if (b == NULL)
    2171             :                 return;
    2172     5501114 :         assert(is_oid_nil(o) || o + BATcount(b) <= GDK_oid_max);
    2173     5501114 :         if (ATOMtype(b->ttype) == TYPE_oid) {
    2174     4756381 :                 b->tseqbase = o;
    2175             : 
    2176             :                 /* adapt keyness */
    2177     4756381 :                 if (BATtvoid(b)) {
    2178     4731433 :                         b->tsorted = true;
    2179     4731433 :                         if (is_oid_nil(o)) {
    2180         112 :                                 b->tkey = b->batCount <= 1;
    2181         112 :                                 b->tnonil = b->batCount == 0;
    2182         112 :                                 b->tnil = b->batCount > 0;
    2183         112 :                                 b->trevsorted = true;
    2184         112 :                                 b->tnosorted = b->tnorevsorted = 0;
    2185         112 :                                 if (!b->tkey) {
    2186           0 :                                         b->tnokey[0] = 0;
    2187           0 :                                         b->tnokey[1] = 1;
    2188             :                                 } else {
    2189         112 :                                         b->tnokey[0] = b->tnokey[1] = 0;
    2190             :                                 }
    2191             :                         } else {
    2192     4731321 :                                 if (!b->tkey) {
    2193       15809 :                                         b->tkey = true;
    2194       15809 :                                         b->tnokey[0] = b->tnokey[1] = 0;
    2195             :                                 }
    2196     4731321 :                                 b->tnonil = true;
    2197     4731321 :                                 b->tnil = false;
    2198     4731321 :                                 b->trevsorted = b->batCount <= 1;
    2199     4731321 :                                 if (!b->trevsorted)
    2200       16104 :                                         b->tnorevsorted = 1;
    2201             :                         }
    2202             :                 }
    2203             :         } else {
    2204      744733 :                 assert(o == oid_nil);
    2205      744733 :                 b->tseqbase = oid_nil;
    2206             :         }
    2207             : }
    2208             : 
    2209             : /*
    2210             :  * @- Change the BAT access permissions (read, append, write)
    2211             :  * Regrettably, BAT access-permissions, persistent status and memory
    2212             :  * map modes, interact in ways that makes one's brain sizzle. This
    2213             :  * makes BATsetaccess and TMcommit (where a change in BAT persistence
    2214             :  * mode is made permanent) points in which the memory map status of
    2215             :  * bats needs to be carefully re-assessed and ensured.
    2216             :  *
    2217             :  * Another complication is the fact that during commit, concurrent
    2218             :  * users may access the heaps, such that the simple solution
    2219             :  * unmap;re-map is out of the question.
    2220             :  * Even worse, it is not possible to even rename an open mmap file in
    2221             :  * Windows. For this purpose, we dropped the old .priv scheme, which
    2222             :  * relied on file moves. Now, the file that is opened with mmap is
    2223             :  * always the X file, in case of newstorage=STORE_PRIV, we save in a
    2224             :  * new file X.new
    2225             :  *
    2226             :  * we must consider the following dimensions:
    2227             :  *
    2228             :  * persistence:
    2229             :  *     not simply the current persistence mode but whether the bat *was*
    2230             :  *     present at the last commit point (BBP status & BBPEXISTING).
    2231             :  *     The crucial issue is namely whether we must guarantee recovery
    2232             :  *     to a previous sane state.
    2233             :  *
    2234             :  * access:
    2235             :  *     whether the BAT is BAT_READ or BAT_WRITE. Note that BAT_APPEND
    2236             :  *     is usually the same as BAT_READ (as our concern are only data pages
    2237             :  *     that already existed at the last commit).
    2238             :  *
    2239             :  * storage:
    2240             :  *     the current way the heap file X is memory-mapped;
    2241             :  *     STORE_MMAP uses direct mapping (so dirty pages may be flushed
    2242             :  *     at any time to disk), STORE_PRIV uses copy-on-write.
    2243             :  *
    2244             :  * newstorage:
    2245             :  *     the current save-regime. STORE_MMAP calls msync() on the heap X,
    2246             :  *     whereas STORE_PRIV writes the *entire* heap in a file: X.new
    2247             :  *     If a BAT is loaded from disk, the field newstorage is used
    2248             :  *     to set storage as well (so before change-access and commit-
    2249             :  *     persistence mayhem, we always have newstorage=storage).
    2250             :  *
    2251             :  * change-access:
    2252             :  *     what happens if the bat-access mode is changed from
    2253             :  *     BAT_READ into BAT_WRITE (or vice versa).
    2254             :  *
    2255             :  * commit-persistence:
    2256             :  *     what happens during commit if the bat-persistence mode was
    2257             :  *     changed (from TRANSIENT into PERSISTENT, or vice versa).
    2258             :  *
    2259             :  * this is the scheme:
    2260             :  *
    2261             :  *  persistence access    newstorage storage    change-access commit-persistence
    2262             :  *  =========== ========= ========== ========== ============= ==================
    2263             :  * 0 transient  BAT_READ  STORE_MMAP STORE_MMAP =>2           =>4
    2264             :  * 1 transient  BAT_READ  STORE_PRIV STORE_PRIV =>3           =>5
    2265             :  * 2 transient  BAT_WRITE STORE_MMAP STORE_MMAP =>0           =>6+
    2266             :  * 3 transient  BAT_WRITE STORE_PRIV STORE_PRIV =>1           =>7
    2267             :  * 4 persistent BAT_READ  STORE_MMAP STORE_MMAP =>6+          =>0
    2268             :  * 5 persistent BAT_READ  STORE_PRIV STORE_PRIV =>7           =>1
    2269             :  * 6 persistent BAT_WRITE STORE_PRIV STORE_MMAP del X.new=>4+ del X.new;=>2+
    2270             :  * 7 persistent BAT_WRITE STORE_PRIV STORE_PRIV =>5           =>3
    2271             :  *
    2272             :  * exception states:
    2273             :  * a transient  BAT_READ  STORE_PRIV STORE_MMAP =>b           =>c
    2274             :  * b transient  BAT_WRITE STORE_PRIV STORE_MMAP =>a           =>6
    2275             :  * c persistent BAT_READ  STORE_PRIV STORE_MMAP =>6           =>a
    2276             :  *
    2277             :  * (+) indicates that we must ensure that the heap gets saved in its new mode
    2278             :  *
    2279             :  * Note that we now allow a heap with save-regime STORE_PRIV that was
    2280             :  * actually mapped STORE_MMAP. In effect, the potential corruption of
    2281             :  * the X file is compensated by writing out full X.new files that take
    2282             :  * precedence.  When transitioning out of this state towards one with
    2283             :  * both storage regime and OS as STORE_MMAP we need to move the X.new
    2284             :  * files into the backup directory. Then msync the X file and (on
    2285             :  * success) remove the X.new; see backup_new().
    2286             :  *
    2287             :  * Exception states are only reachable if the commit fails and those
    2288             :  * new persistent bats have already been processed (but never become
    2289             :  * part of a committed state). In that case a transition 2=>6 may end
    2290             :  * up 2=>b.  Exception states a and c are reachable from b.
    2291             :  *
    2292             :  * Errors in HEAPchangeaccess() can be handled atomically inside the
    2293             :  * routine.  The work on changing mmap modes HEAPcommitpersistence()
    2294             :  * is done during the BBPsync() for all bats that are newly persistent
    2295             :  * (BBPNEW). After the TMcommit(), it is done for those bats that are
    2296             :  * no longer persistent after the commit (BBPDELETED), only if it
    2297             :  * succeeds.  Such transient bats cannot be processed before the
    2298             :  * commit, because the commit may fail and then the more unsafe
    2299             :  * transient mmap modes would be present on a persistent bat.
    2300             :  *
    2301             :  * See dirty_bat() in BBPsync() -- gdk_bbp.c and epilogue() in
    2302             :  * gdk_tm.c.
    2303             :  *
    2304             :  * Including the exception states, we have 11 of the 16
    2305             :  * combinations. As for the 5 avoided states, all four
    2306             :  * (persistence,access) states with (STORE_MMAP,STORE_PRIV) are
    2307             :  * omitted (this would amount to an msync() save regime on a
    2308             :  * copy-on-write heap -- which does not work). The remaining avoided
    2309             :  * state is the patently unsafe
    2310             :  * (persistent,BAT_WRITE,STORE_MMAP,STORE_MMAP).
    2311             :  *
    2312             :  * Note that after a server restart exception states are gone, as on
    2313             :  * BAT loads the saved descriptor is inspected again (which will
    2314             :  * reproduce the state at the last succeeded commit).
    2315             :  *
    2316             :  * To avoid exception states, a TMsubcommit protocol would need to be
    2317             :  * used which is too heavy for BATsetaccess().
    2318             :  *
    2319             :  * Note that this code is not about making heaps mmap-ed in the first
    2320             :  * place.  It is just about determining which flavor of mmap should be
    2321             :  * used. The MAL user is oblivious of such details.
    2322             :  */
    2323             : 
    2324             : /* rather than deleting X.new, we comply with the commit protocol and
    2325             :  * move it to backup storage */
    2326             : static gdk_return
    2327           0 : backup_new(Heap *hp, bool lock)
    2328             : {
    2329           0 :         int batret, bakret, ret = -1;
    2330           0 :         char *batpath, *bakpath;
    2331           0 :         struct stat st;
    2332             : 
    2333           0 :         char *bak_filename = NULL;
    2334           0 :         if ((bak_filename = strrchr(hp->filename, DIR_SEP)) != NULL)
    2335           0 :                 bak_filename++;
    2336             :         else
    2337             :                 bak_filename = hp->filename;
    2338             :         /* check for an existing X.new in BATDIR, BAKDIR and SUBDIR */
    2339           0 :         batpath = GDKfilepath(hp->farmid, BATDIR, hp->filename, "new");
    2340           0 :         bakpath = GDKfilepath(hp->farmid, BAKDIR, bak_filename, "new");
    2341           0 :         if (batpath != NULL && bakpath != NULL) {
    2342             :                 /* file actions here interact with the global commits */
    2343           0 :                 if (lock)
    2344           0 :                         BBPtmlock();
    2345             : 
    2346           0 :                 batret = MT_stat(batpath, &st);
    2347           0 :                 bakret = MT_stat(bakpath, &st);
    2348             : 
    2349           0 :                 if (batret == 0 && bakret) {
    2350             :                         /* no backup yet, so move the existing X.new there out
    2351             :                          * of the way */
    2352           0 :                         if ((ret = MT_rename(batpath, bakpath)) < 0)
    2353           0 :                                 GDKsyserror("backup_new: rename %s to %s failed\n",
    2354             :                                             batpath, bakpath);
    2355           0 :                         TRC_DEBUG(IO_, "rename(%s,%s) = %d\n", batpath, bakpath, ret);
    2356           0 :                 } else if (batret == 0) {
    2357             :                         /* there is a backup already; just remove the X.new */
    2358           0 :                         if ((ret = MT_remove(batpath)) != 0)
    2359           0 :                                 GDKsyserror("backup_new: remove %s failed\n", batpath);
    2360           0 :                         TRC_DEBUG(IO_, "remove(%s) = %d\n", batpath, ret);
    2361             :                 } else {
    2362             :                         ret = 0;
    2363             :                 }
    2364           0 :                 if (lock)
    2365           0 :                         BBPtmunlock();
    2366             :         }
    2367           0 :         GDKfree(batpath);
    2368           0 :         GDKfree(bakpath);
    2369           0 :         return ret ? GDK_FAIL : GDK_SUCCEED;
    2370             : }
    2371             : 
    2372             : #define ACCESSMODE(wr,rd) ((wr)?BAT_WRITE:(rd)?BAT_READ:-1)
    2373             : 
    2374             : /* transition heap from readonly to writable */
    2375             : static storage_t
    2376     4610705 : HEAPchangeaccess(Heap *hp, int dstmode, bool existing)
    2377             : {
    2378     4610705 :         if (hp->base == NULL || hp->newstorage == STORE_MEM || !existing || dstmode == -1)
    2379     4610705 :                 return hp->newstorage;       /* 0<=>2,1<=>3,a<=>b */
    2380             : 
    2381           0 :         if (dstmode == BAT_WRITE) {
    2382           0 :                 if (hp->storage != STORE_PRIV)
    2383           0 :                         hp->dirty = true;    /* exception c does not make it dirty */
    2384           0 :                 return STORE_PRIV;      /* 4=>6,5=>7,c=>6 persistent BAT_WRITE needs STORE_PRIV */
    2385             :         }
    2386           0 :         if (hp->storage == STORE_MMAP) {     /* 6=>4 */
    2387           0 :                 hp->dirty = true;
    2388           0 :                 return backup_new(hp, true) != GDK_SUCCEED ? STORE_INVALID : STORE_MMAP;        /* only called for existing bats */
    2389             :         }
    2390             :         return hp->storage;  /* 7=>5 */
    2391             : }
    2392             : 
    2393             : /* heap changes persistence mode (at commit point) */
    2394             : static storage_t
    2395      202430 : HEAPcommitpersistence(Heap *hp, bool writable, bool existing)
    2396             : {
    2397      202430 :         if (existing) {         /* existing, ie will become transient */
    2398       60252 :                 if (hp->storage == STORE_MMAP && hp->newstorage == STORE_PRIV && writable) {      /* 6=>2 */
    2399           0 :                         hp->dirty = true;
    2400           0 :                         return backup_new(hp, false) != GDK_SUCCEED ? STORE_INVALID : STORE_MMAP;       /* only called for existing bats */
    2401             :                 }
    2402       60252 :                 return hp->newstorage;       /* 4=>0,5=>1,7=>3,c=>a no change */
    2403             :         }
    2404             :         /* !existing, ie will become persistent */
    2405      142178 :         if (hp->newstorage == STORE_MEM)
    2406             :                 return hp->newstorage;
    2407         779 :         if (hp->newstorage == STORE_MMAP && !writable)
    2408             :                 return STORE_MMAP;      /* 0=>4 STORE_MMAP */
    2409             : 
    2410           0 :         if (hp->newstorage == STORE_MMAP)
    2411           0 :                 hp->dirty = true;    /* 2=>6 */
    2412             :         return STORE_PRIV;      /* 1=>5,2=>6,3=>7,a=>c,b=>6 states */
    2413             : }
    2414             : 
    2415             : 
    2416             : #define ATOMappendpriv(t, h) (ATOMstorage(t) != TYPE_str /*|| GDK_ELIMDOUBLES(h) */)
    2417             : 
    2418             : /* change the heap modes at a commit */
    2419             : gdk_return
    2420      179264 : BATcheckmodes(BAT *b, bool existing)
    2421             : {
    2422      179264 :         storage_t m1 = STORE_MEM, m3 = STORE_MEM;
    2423      179264 :         bool dirty = false, wr;
    2424             : 
    2425      179264 :         BATcheck(b, GDK_FAIL);
    2426             : 
    2427      179264 :         wr = (b->batRestricted == BAT_WRITE);
    2428      179264 :         if (b->ttype) {
    2429      179264 :                 m1 = HEAPcommitpersistence(b->theap, wr, existing);
    2430      179264 :                 dirty |= (b->theap->newstorage != m1);
    2431             :         }
    2432             : 
    2433      179264 :         if (b->tvheap) {
    2434       23166 :                 bool ta = (b->batRestricted == BAT_APPEND) && ATOMappendpriv(b->ttype, b->tvheap);
    2435       23166 :                 m3 = HEAPcommitpersistence(b->tvheap, wr || ta, existing);
    2436       23166 :                 dirty |= (b->tvheap->newstorage != m3);
    2437             :         }
    2438      179264 :         if (m1 == STORE_INVALID || m3 == STORE_INVALID)
    2439             :                 return GDK_FAIL;
    2440             : 
    2441      179264 :         if (dirty) {
    2442           0 :                 b->theap->newstorage = m1;
    2443           0 :                 if (b->tvheap)
    2444           0 :                         b->tvheap->newstorage = m3;
    2445             :         }
    2446             :         return GDK_SUCCEED;
    2447             : }
    2448             : 
    2449             : BAT *
    2450     5815653 : BATsetaccess(BAT *b, restrict_t newmode)
    2451             : {
    2452     5815653 :         restrict_t bakmode;
    2453             : 
    2454     5815653 :         BATcheck(b, NULL);
    2455     5815653 :         if (newmode != BAT_READ &&
    2456       19060 :             (isVIEW(b) || (ATOMIC_GET(&b->theap->refs) & HEAPREFS) > 1)) {
    2457           0 :                 BAT *bn = COLcopy(b, b->ttype, true, b->batRole);
    2458           0 :                 BBPunfix(b->batCacheid);
    2459           0 :                 if (bn == NULL)
    2460             :                         return NULL;
    2461             :                 b = bn;
    2462             :         }
    2463     5815653 :         MT_lock_set(&b->theaplock);
    2464     5814639 :         bakmode = b->batRestricted;
    2465     5814639 :         if (bakmode != newmode) {
    2466     3988476 :                 bool existing = (BBP_status(b->batCacheid) & BBPEXISTING) != 0;
    2467     3988476 :                 bool wr = (newmode == BAT_WRITE);
    2468     3988476 :                 bool rd = (bakmode == BAT_WRITE);
    2469     3988476 :                 storage_t m1 = STORE_MEM, m3 = STORE_MEM;
    2470     3988476 :                 storage_t b1 = STORE_MEM, b3 = STORE_MEM;
    2471             : 
    2472     3988476 :                 if (b->theap->parentid == b->batCacheid) {
    2473     3986896 :                         b1 = b->theap->newstorage;
    2474     3997139 :                         m1 = HEAPchangeaccess(b->theap, ACCESSMODE(wr, rd), existing);
    2475             :                 }
    2476     3988435 :                 if (b->tvheap && b->tvheap->parentid == b->batCacheid) {
    2477      623102 :                         bool ta = (newmode == BAT_APPEND && ATOMappendpriv(b->ttype, b->tvheap));
    2478      623102 :                         b3 = b->tvheap->newstorage;
    2479     1246155 :                         m3 = HEAPchangeaccess(b->tvheap, ACCESSMODE(wr && ta, rd && ta), existing);
    2480             :                 }
    2481     3988311 :                 if (m1 == STORE_INVALID || m3 == STORE_INVALID) {
    2482     1312519 :                         MT_lock_unset(&b->theaplock);
    2483     1312852 :                         BBPunfix(b->batCacheid);
    2484     1312852 :                         return NULL;
    2485             :                 }
    2486             : 
    2487             :                 /* set new access mode and mmap modes */
    2488     2675792 :                 b->batRestricted = newmode;
    2489     2675792 :                 if (b->theap->parentid == b->batCacheid)
    2490     2675455 :                         b->theap->newstorage = m1;
    2491     2675792 :                 if (b->tvheap && b->tvheap->parentid == b->batCacheid)
    2492      603396 :                         b->tvheap->newstorage = m3;
    2493             : 
    2494     2675792 :                 MT_lock_unset(&b->theaplock);
    2495     2675563 :                 if (existing && !isVIEW(b) && BBPsave(b) != GDK_SUCCEED) {
    2496             :                         /* roll back all changes */
    2497           0 :                         MT_lock_set(&b->theaplock);
    2498           0 :                         b->batRestricted = bakmode;
    2499           0 :                         b->theap->newstorage = b1;
    2500           0 :                         if (b->tvheap)
    2501           0 :                                 b->tvheap->newstorage = b3;
    2502           0 :                         MT_lock_unset(&b->theaplock);
    2503           0 :                         BBPunfix(b->batCacheid);
    2504           0 :                         return NULL;
    2505             :                 }
    2506             :         } else {
    2507     1826163 :                 MT_lock_unset(&b->theaplock);
    2508             :         }
    2509             :         return b;
    2510             : }
    2511             : 
    2512             : restrict_t
    2513           0 : BATgetaccess(BAT *b)
    2514             : {
    2515           0 :         BATcheck(b, BAT_WRITE);
    2516           0 :         MT_lock_set(&b->theaplock);
    2517           0 :         restrict_t restricted = b->batRestricted;
    2518           0 :         MT_lock_unset(&b->theaplock);
    2519           0 :         return restricted;
    2520             : }
    2521             : 
    2522             : /*
    2523             :  * @- change BAT persistency (persistent,session,transient)
    2524             :  * In the past, we prevented BATS with certain types from being saved at all:
    2525             :  * - BATs of BATs, as having recursive bats creates cascading
    2526             :  *   complexities in commits/aborts.
    2527             :  * - any atom with refcounts, as the BBP has no overview of such
    2528             :  *   user-defined refcounts.
    2529             :  * - pointer types, as the values they point to are bound to be transient.
    2530             :  *
    2531             :  * However, nowadays we do allow such saves, as the BBP swapping
    2532             :  * mechanism was altered to be able to save transient bats temporarily
    2533             :  * to disk in order to make room.  Thus, we must be able to save any
    2534             :  * transient BAT to disk.
    2535             :  *
    2536             :  * What we don't allow is to make such bats persistent.
    2537             :  *
    2538             :  * Although the persistent state does influence the allowed mmap
    2539             :  * modes, this only goes for the *real* committed persistent
    2540             :  * state. Making the bat persistent with BATmode does not matter for
    2541             :  * the heap modes until the commit point is reached. So we do not need
    2542             :  * to do anything with heap modes yet at this point.
    2543             :  */
    2544             : gdk_return
    2545      430179 : BATmode(BAT *b, bool transient)
    2546             : {
    2547      430179 :         BATcheck(b, GDK_FAIL);
    2548             : 
    2549             :         /* can only make a bat PERSISTENT if its role is already
    2550             :          * PERSISTENT */
    2551      430179 :         assert(transient || b->batRole == PERSISTENT);
    2552             :         /* cannot make a view PERSISTENT */
    2553      245593 :         assert(transient || !isVIEW(b));
    2554             : 
    2555      430179 :         if (b->batRole == TRANSIENT && !transient) {
    2556           0 :                 GDKerror("cannot change mode of BAT in TRANSIENT farm.\n");
    2557           0 :                 return GDK_FAIL;
    2558             :         }
    2559             : 
    2560      430179 :         BATiter bi = bat_iterator(b);
    2561      430179 :         bool mustrelease = false;
    2562      430179 :         bool mustretain = false;
    2563      430179 :         bat bid = b->batCacheid;
    2564             : 
    2565      430179 :         if (transient != bi.transient) {
    2566      430179 :                 if (!transient) {
    2567      245593 :                         if (ATOMisdescendant(b->ttype, TYPE_ptr)) {
    2568           0 :                                 GDKerror("%s type implies that %s[%s] "
    2569             :                                          "cannot be made persistent.\n",
    2570             :                                          ATOMname(b->ttype), BATgetId(b),
    2571             :                                          ATOMname(b->ttype));
    2572           0 :                                 bat_iterator_end(&bi);
    2573           0 :                                 return GDK_FAIL;
    2574             :                         }
    2575             :                 }
    2576             : 
    2577             :                 /* we need to delay the calls to BBPretain and
    2578             :                  * BBPrelease until after we have released our reference
    2579             :                  * to the heaps (i.e. until after bat_iterator_end),
    2580             :                  * because in either case, BBPfree can be called (either
    2581             :                  * directly here or in BBPtrim) which waits for the heap
    2582             :                  * reference to come down.  BBPretain calls incref which
    2583             :                  * waits until the trim that is waiting for us is done,
    2584             :                  * so that causes deadlock, and BBPrelease can call
    2585             :                  * BBPfree which causes deadlock with a single thread */
    2586      184586 :                 if (!transient) {
    2587             :                         /* persistent BATs get a logical reference */
    2588             :                         mustretain = true;
    2589      184586 :                 } else if (!bi.transient) {
    2590             :                         /* transient BATs loose their logical reference */
    2591      184586 :                         mustrelease = true;
    2592             :                 }
    2593      430179 :                 MT_lock_set(&GDKswapLock(bid));
    2594      430179 :                 if (!transient) {
    2595      245593 :                         if (BBP_status(bid) & BBPDELETED) {
    2596           0 :                                 BBP_status_on(bid, BBPEXISTING);
    2597           0 :                                 BBP_status_off(bid, BBPDELETED);
    2598             :                         } else
    2599      245593 :                                 BBP_status_on(bid, BBPNEW);
    2600      184586 :                 } else if (!bi.transient) {
    2601      184586 :                         if (!(BBP_status(bid) & BBPNEW))
    2602       61981 :                                 BBP_status_on(bid, BBPDELETED);
    2603      184586 :                         BBP_status_off(bid, BBPPERSISTENT);
    2604             :                 }
    2605             :                 /* session bats or persistent bats that did not
    2606             :                  * witness a commit yet may have been saved */
    2607      430179 :                 MT_lock_set(&b->theaplock);
    2608      430179 :                 if (b->batCopiedtodisk) {
    2609       51935 :                         if (!transient) {
    2610         570 :                                 BBP_status_off(bid, BBPTMP);
    2611             :                         } else {
    2612             :                                 /* TMcommit must remove it to
    2613             :                                  * guarantee free space */
    2614       51365 :                                 BBP_status_on(bid, BBPTMP);
    2615             :                         }
    2616             :                 }
    2617      430179 :                 b->batTransient = transient;
    2618      430179 :                 MT_lock_unset(&b->theaplock);
    2619      430179 :                 MT_lock_unset(&GDKswapLock(bid));
    2620             :         }
    2621      430179 :         bat_iterator_end(&bi);
    2622             :         /* retain/release after bat_iterator_end because of refs to heaps */
    2623      430179 :         if (mustretain)
    2624      245593 :                 BBPretain(bid);
    2625      184586 :         else if (mustrelease)
    2626      184586 :                 BBPrelease(bid);
    2627             :         return GDK_SUCCEED;
    2628             : }
    2629             : 
    2630             : /* BATassertProps checks whether properties are set correctly.  Under
    2631             :  * no circumstances will it change any properties.  Note that the
    2632             :  * "nil" property is not actually used anywhere, but it is checked. */
    2633             : 
    2634             : #ifdef NDEBUG
    2635             : /* assertions are disabled, turn failing tests into a message */
    2636             : #undef assert
    2637             : #define assert(test)    ((void) ((test) || (TRC_CRITICAL_ENDIF(CHECK_, "Assertion `%s' failed\n", #test), 0)))
    2638             : #endif
    2639             : 
    2640             : static void
    2641   177937944 : assert_ascii(const char *s)
    2642             : {
    2643   355875888 :         if (!strNil(s)) {
    2644  3504997879 :                 while (*s) {
    2645  3374048829 :                         assert((*s & 0x80) == 0);
    2646  3374048829 :                         s++;
    2647             :                 }
    2648             :         }
    2649   177937944 : }
    2650             : 
    2651             : /* Assert that properties are set correctly.
    2652             :  *
    2653             :  * A BAT can have a bunch of properties set.  Mostly, the property
    2654             :  * bits are set if we *know* the property holds, and not set if we
    2655             :  * don't know whether the property holds (or if we know it doesn't
    2656             :  * hold).  All properties are per column.
    2657             :  *
    2658             :  * The properties currently maintained are:
    2659             :  *
    2660             :  * seqbase      Only valid for TYPE_oid and TYPE_void columns: each
    2661             :  *              value in the column is exactly one more than the
    2662             :  *              previous value, starting at position 0 with the value
    2663             :  *              stored in this property.
    2664             :  *              This implies sorted, key, nonil (which therefore need
    2665             :  *              to be set).
    2666             :  * nil          There is at least one NIL value in the column.
    2667             :  * nonil        There are no NIL values in the column.
    2668             :  * key          All values in the column are distinct.
    2669             :  * sorted       The column is sorted (ascending).  If also revsorted,
    2670             :  *              then all values are equal.
    2671             :  * revsorted    The column is reversely sorted (descending).  If
    2672             :  *              also sorted, then all values are equal.
    2673             :  * nosorted     BUN position which proofs not sorted (given position
    2674             :  *              and one before are not ordered correctly).
    2675             :  * norevsorted  BUN position which proofs not revsorted (given position
    2676             :  *              and one before are not ordered correctly).
    2677             :  * nokey        Pair of BUN positions that proof not all values are
    2678             :  *              distinct (i.e. values at given locations are equal).
    2679             :  * ascii        Only valid for TYPE_str columns: all strings in the column
    2680             :  *              are ASCII, i.e. the UTF-8 encoding for all characters is a
    2681             :  *              single byte.
    2682             :  *
    2683             :  * Note that the functions BATtseqbase and BATkey also set more
    2684             :  * properties than you might suspect.  When setting properties on a
    2685             :  * newly created and filled BAT, you may want to first make sure the
    2686             :  * batCount is set correctly (e.g. by calling BATsetcount), then use
    2687             :  * BATtseqbase and BATkey, and finally set the other properties.
    2688             :  *
    2689             :  * For a view, we cannot check all properties, since it is possible with
    2690             :  * the way the SQL layer works, that a parent BAT gets changed, changing
    2691             :  * the properties, while there is a view.  The view is supposed to look
    2692             :  * at only the non-changing part of the BAT (through candidate lists),
    2693             :  * but this means that the properties of the view might not be correct.
    2694             :  * For this reason, for views, we skip all property checking that looks
    2695             :  * at the BAT content.
    2696             :  */
    2697             : 
    2698             : void
    2699    12750586 : BATassertProps(BAT *b)
    2700             : {
    2701    12750586 :         unsigned bbpstatus;
    2702    12750586 :         BUN p, q;
    2703    12750586 :         int (*cmpf)(const void *, const void *);
    2704    12750586 :         int cmp;
    2705    12750586 :         const void *prev = NULL, *valp, *nilp;
    2706    12750586 :         char filename[sizeof(b->theap->filename)];
    2707    12750586 :         bool isview1, isview2;
    2708             : 
    2709             :         /* do the complete check within a lock */
    2710    12750586 :         MT_lock_set(&b->theaplock);
    2711             : 
    2712             :         /* general BAT sanity */
    2713    12716079 :         assert(b != NULL);
    2714    12716079 :         assert(b->batCacheid > 0);
    2715    12716079 :         assert(b->batCacheid < getBBPsize());
    2716    12738486 :         assert(b == BBP_desc(b->batCacheid));
    2717    12738486 :         assert(b->batCount >= b->batInserted);
    2718             : 
    2719             :         /* headless */
    2720    12738486 :         assert(b->hseqbase <= GDK_oid_max); /* non-nil seqbase */
    2721    12738486 :         assert(b->hseqbase + BATcount(b) <= GDK_oid_max);
    2722             : 
    2723    12738486 :         isview1 = b->theap->parentid != b->batCacheid;
    2724    12738486 :         isview2 = b->tvheap && b->tvheap->parentid != b->batCacheid;
    2725             : 
    2726    12738486 :         bbpstatus = BBP_status(b->batCacheid);
    2727             :         /* only at most one of BBPDELETED, BBPEXISTING, BBPNEW may be set */
    2728    12738486 :         assert(((bbpstatus & BBPDELETED) != 0) +
    2729             :                ((bbpstatus & BBPEXISTING) != 0) +
    2730             :                ((bbpstatus & BBPNEW) != 0) <= 1);
    2731             : 
    2732    12738486 :         assert(b->ttype >= TYPE_void);
    2733    12738486 :         assert(b->ttype < GDKatomcnt);
    2734    12738486 :         assert(isview1 ||
    2735             :                b->ttype == TYPE_void ||
    2736             :                BBPfarms[b->theap->farmid].roles & (1 << b->batRole));
    2737    12738486 :         assert(isview2 ||
    2738             :                b->tvheap == NULL ||
    2739             :                (BBPfarms[b->tvheap->farmid].roles & (1 << b->batRole)));
    2740             : 
    2741    12738486 :         cmpf = ATOMcompare(b->ttype);
    2742    12738486 :         nilp = ATOMnilptr(b->ttype);
    2743             : 
    2744    12738486 :         assert(isview1 || b->theap->free >= tailsize(b, BATcount(b)));
    2745    12738486 :         if (b->ttype != TYPE_void) {
    2746     9847275 :                 assert(b->batCount <= b->batCapacity);
    2747     9847275 :                 assert(isview1 || b->theap->size >= b->theap->free);
    2748     9847275 :                 if (ATOMstorage(b->ttype) == TYPE_msk) {
    2749             :                         /* 32 values per 4-byte word (that's not the
    2750             :                          * same as 8 values per byte...) */
    2751        4078 :                         assert(isview1 || b->theap->size >= 4 * ((b->batCapacity + 31) / 32));
    2752             :                 } else
    2753     9843197 :                         assert(isview1 || b->theap->size >> b->tshift >= b->batCapacity);
    2754             :         }
    2755    12738486 :         if (!isview1) {
    2756     9586198 :                 strconcat_len(filename, sizeof(filename),
    2757     9586198 :                               BBP_physical(b->theap->parentid),
    2758     1716908 :                               b->ttype == TYPE_str ? b->twidth == 1 ? ".tail1" : b->twidth == 2 ? ".tail2" :
    2759             : #if SIZEOF_VAR_T == 8
    2760             :                               b->twidth == 4 ? ".tail4" :
    2761             : #endif
    2762             :                               ".tail" : ".tail",
    2763             :                               NULL);
    2764     9593401 :                 assert(strcmp(b->theap->filename, filename) == 0);
    2765             :         }
    2766    12745689 :         if (!isview2 && b->tvheap) {
    2767     1619844 :                 strconcat_len(filename, sizeof(filename),
    2768     1619844 :                               BBP_physical(b->tvheap->parentid),
    2769             :                               ".theap",
    2770             :                               NULL);
    2771     1619761 :                 assert(strcmp(b->tvheap->filename, filename) == 0);
    2772             :         }
    2773             : 
    2774             :         /* void, str and blob imply varsized */
    2775    12745606 :         if (ATOMstorage(b->ttype) == TYPE_str ||
    2776             :             ATOMstorage(b->ttype) == TYPE_blob)
    2777     2308617 :                 assert(b->tvheap != NULL);
    2778             :         /* other "known" types are not varsized */
    2779    12745606 :         if (ATOMstorage(b->ttype) > TYPE_void &&
    2780             :             ATOMstorage(b->ttype) < TYPE_str)
    2781     7551481 :                 assert(b->tvheap == NULL);
    2782             :         /* shift and width have a particular relationship */
    2783    12745606 :         if (ATOMstorage(b->ttype) == TYPE_str)
    2784     2306385 :                 assert(b->twidth >= 1 && b->twidth <= ATOMsize(b->ttype));
    2785             :         else
    2786    10439221 :                 assert(b->twidth == ATOMsize(b->ttype));
    2787    12745606 :         assert(b->tseqbase <= oid_nil);
    2788             :         /* only oid/void columns can be dense */
    2789    12745606 :         assert(is_oid_nil(b->tseqbase) || b->ttype == TYPE_oid || b->ttype == TYPE_void);
    2790             :         /* a column cannot both have and not have NILs */
    2791    12745606 :         assert(!b->tnil || !b->tnonil);
    2792             :         /* only string columns can be ASCII */
    2793    12745606 :         assert(!b->tascii || ATOMstorage(b->ttype) == TYPE_str);
    2794    12745606 :         if (b->ttype == TYPE_void) {
    2795     2882335 :                 assert(b->tshift == 0);
    2796     2882335 :                 assert(b->twidth == 0);
    2797     2882335 :                 assert(b->tsorted);
    2798     2882335 :                 if (is_oid_nil(b->tseqbase)) {
    2799         247 :                         assert(b->tvheap == NULL);
    2800         247 :                         assert(BATcount(b) == 0 || !b->tnonil);
    2801         247 :                         assert(BATcount(b) <= 1 || !b->tkey);
    2802         247 :                         assert(b->trevsorted);
    2803             :                 } else {
    2804     2882088 :                         if (b->tvheap != NULL) {
    2805             :                                 /* candidate list with exceptions */
    2806       37876 :                                 assert(b->batRole == TRANSIENT || b->batRole == SYSTRANS);
    2807       37876 :                                 assert(b->tvheap->free <= b->tvheap->size);
    2808       37876 :                                 assert(b->tvheap->free >= sizeof(ccand_t));
    2809       37876 :                                 assert((negoid_cand(b) && ccand_free(b) % SIZEOF_OID == 0) || mask_cand(b));
    2810       37876 :                                 if (negoid_cand(b) && ccand_free(b) > 0) {
    2811         198 :                                         const oid *oids = (const oid *) ccand_first(b);
    2812         198 :                                         q = ccand_free(b) / SIZEOF_OID;
    2813         198 :                                         assert(oids != NULL);
    2814         198 :                                         assert(b->tseqbase + BATcount(b) + q <= GDK_oid_max);
    2815             :                                         /* exceptions within range */
    2816         198 :                                         assert(oids[0] >= b->tseqbase);
    2817         198 :                                         assert(oids[q - 1] < b->tseqbase + BATcount(b) + q);
    2818             :                                         /* exceptions sorted */
    2819      188692 :                                         for (p = 1; p < q; p++)
    2820      188494 :                                                 assert(oids[p - 1] < oids[p]);
    2821             :                                 }
    2822             :                         }
    2823     2882088 :                         assert(b->tseqbase + b->batCount <= GDK_oid_max);
    2824     2882088 :                         assert(BATcount(b) == 0 || !b->tnil);
    2825     2882088 :                         assert(BATcount(b) <= 1 || !b->trevsorted);
    2826     2882088 :                         assert(b->tkey);
    2827     2882088 :                         assert(b->tnonil);
    2828             :                 }
    2829     2882335 :                 MT_lock_unset(&b->theaplock);
    2830     7418199 :                 return;
    2831             :         }
    2832             : 
    2833     9863271 :         BATiter bi  = bat_iterator_nolock(b);
    2834             : 
    2835     9863271 :         if (BATtdense(b)) {
    2836      189562 :                 assert(b->tseqbase + b->batCount <= GDK_oid_max);
    2837      189562 :                 assert(b->ttype == TYPE_oid);
    2838      189562 :                 assert(b->tsorted);
    2839      189562 :                 assert(b->tkey);
    2840      189562 :                 assert(b->tnonil);
    2841      189562 :                 if ((q = b->batCount) != 0) {
    2842      161887 :                         const oid *o = (const oid *) Tloc(b, 0);
    2843      161887 :                         assert(*o == b->tseqbase);
    2844    26093250 :                         for (p = 1; p < q; p++)
    2845    25931363 :                                 assert(o[p - 1] + 1 == o[p]);
    2846             :                 }
    2847      189562 :                 MT_lock_unset(&b->theaplock);
    2848      189557 :                 return;
    2849             :         }
    2850     9673709 :         assert(1 << b->tshift == b->twidth);
    2851             :         /* only linear atoms can be sorted */
    2852     9673709 :         assert(!b->tsorted || ATOMlinear(b->ttype));
    2853     9673709 :         assert(!b->trevsorted || ATOMlinear(b->ttype));
    2854     9673709 :         if (ATOMlinear(b->ttype)) {
    2855     9672430 :                 assert(b->tnosorted == 0 ||
    2856             :                        (b->tnosorted > 0 &&
    2857             :                         b->tnosorted < b->batCount));
    2858     9672430 :                 assert(!b->tsorted || b->tnosorted == 0);
    2859     9672430 :                 if (!isview1 &&
    2860     9672430 :                     !isview2 &&
    2861     1632005 :                     !b->tsorted &&
    2862      113528 :                     b->tnosorted > 0 &&
    2863      113528 :                     b->tnosorted < b->batCount)
    2864      113538 :                         assert(cmpf(BUNtail(bi, b->tnosorted - 1),
    2865             :                                     BUNtail(bi, b->tnosorted)) > 0);
    2866     9672390 :                 assert(b->tnorevsorted == 0 ||
    2867             :                        (b->tnorevsorted > 0 &&
    2868             :                         b->tnorevsorted < b->batCount));
    2869     9672390 :                 assert(!b->trevsorted || b->tnorevsorted == 0);
    2870     9672390 :                 if (!isview1 &&
    2871     6392065 :                     !isview2 &&
    2872     2183623 :                     !b->trevsorted &&
    2873      470136 :                     b->tnorevsorted > 0 &&
    2874      470136 :                     b->tnorevsorted < b->batCount)
    2875      470192 :                         assert(cmpf(BUNtail(bi, b->tnorevsorted - 1),
    2876             :                                     BUNtail(bi, b->tnorevsorted)) < 0);
    2877             :         }
    2878             :         /* if tkey property set, both tnokey values must be 0 */
    2879     9673535 :         assert(!b->tkey || (b->tnokey[0] == 0 && b->tnokey[1] == 0));
    2880     9673535 :         if (!isview1 &&
    2881     9673535 :             !isview2 &&
    2882     1938856 :             !b->tkey &&
    2883     1938856 :             (b->tnokey[0] != 0 || b->tnokey[1] != 0)) {
    2884             :                 /* if tkey not set and tnokey indicates a proof of
    2885             :                  * non-key-ness, make sure the tnokey values are in
    2886             :                  * range and indeed provide a proof */
    2887      522755 :                 assert(b->tnokey[0] != b->tnokey[1]);
    2888      522755 :                 assert(b->tnokey[0] < b->batCount);
    2889      522755 :                 assert(b->tnokey[1] < b->batCount);
    2890      522755 :                 assert(cmpf(BUNtail(bi, b->tnokey[0]),
    2891             :                             BUNtail(bi, b->tnokey[1])) == 0);
    2892             :         }
    2893             :         /* var heaps must have sane sizes */
    2894     9673342 :         assert(b->tvheap == NULL || b->tvheap->free <= b->tvheap->size);
    2895             : 
    2896     9673342 :         if (!b->tkey && !b->tsorted && !b->trevsorted &&
    2897     3594881 :             !b->tnonil && !b->tnil) {
    2898             :                 /* nothing more to prove */
    2899     1464288 :                 MT_lock_unset(&b->theaplock);
    2900     1463276 :                 return;
    2901             :         }
    2902             : 
    2903             :         /* only do a scan if the bat is not a view */
    2904     8209054 :         if (!isview1 && !isview2) {
    2905     5968240 :                 const ValRecord *prop;
    2906     5968240 :                 const void *maxval = NULL;
    2907     5968240 :                 const void *minval = NULL;
    2908     5968240 :                 const void *maxbound = NULL;
    2909     5968240 :                 const void *minbound = NULL;
    2910     5968240 :                 const bool notnull = BATgetprop_nolock(b, GDK_NOT_NULL) != NULL;
    2911     5964640 :                 bool seenmax = false, seenmin = false;
    2912     5964640 :                 bool seennil = false;
    2913             : 
    2914     5964640 :                 if ((prop = BATgetprop_nolock(b, GDK_MAX_BOUND)) != NULL)
    2915          12 :                         maxbound = VALptr(prop);
    2916     5963011 :                 if ((prop = BATgetprop_nolock(b, GDK_MIN_BOUND)) != NULL)
    2917        2488 :                         minbound = VALptr(prop);
    2918     5964644 :                 if (b->tmaxpos != BUN_NONE) {
    2919     1048019 :                         assert(b->tmaxpos < BATcount(b));
    2920     1048019 :                         maxval = BUNtail(bi, b->tmaxpos);
    2921     1048019 :                         assert(cmpf(maxval, nilp) != 0);
    2922             :                 }
    2923     5963259 :                 if (b->tminpos != BUN_NONE) {
    2924     1002666 :                         assert(b->tminpos < BATcount(b));
    2925     1002666 :                         minval = BUNtail(bi, b->tminpos);
    2926     1002666 :                         assert(cmpf(minval, nilp) != 0);
    2927             :                 }
    2928     5961474 :                 if (ATOMstorage(b->ttype) == TYPE_msk) {
    2929             :                         /* for now, don't do extra checks for bit mask */
    2930             :                         ;
    2931     5957456 :                 } else if (b->tsorted || b->trevsorted || !b->tkey) {
    2932             :                         /* if sorted (either way), or we don't have to
    2933             :                          * prove uniqueness, we can do a simple
    2934             :                          * scan */
    2935             :                         /* only call compare function if we have to */
    2936     5938491 :                         bool cmpprv = b->tsorted | b->trevsorted | b->tkey;
    2937             : 
    2938  2472825361 :                         BATloop(b, p, q) {
    2939  2467048459 :                                 valp = BUNtail(bi, p);
    2940  2467048459 :                                 bool isnil = cmpf(valp, nilp) == 0;
    2941  2380451513 :                                 assert(!isnil || !notnull);
    2942  2380451513 :                                 assert(!b->tnonil || !isnil);
    2943  2380451513 :                                 assert(b->ttype != TYPE_flt || !isinf(*(flt*)valp));
    2944  2380451513 :                                 assert(b->ttype != TYPE_dbl || !isinf(*(dbl*)valp));
    2945  2380451513 :                                 if (b->tascii)
    2946   175768507 :                                         assert_ascii(valp);
    2947  2380451392 :                                 if (minbound && !isnil) {
    2948          30 :                                         cmp = cmpf(minbound, valp);
    2949          30 :                                         assert(cmp <= 0);
    2950             :                                 }
    2951  2380451392 :                                 if (maxbound && !isnil) {
    2952          30 :                                         cmp = cmpf(maxbound, valp);
    2953          30 :                                         assert(cmp > 0);
    2954             :                                 }
    2955  2380451392 :                                 if (maxval && !isnil) {
    2956    77617889 :                                         cmp = cmpf(maxval, valp);
    2957    77615827 :                                         assert(cmp >= 0);
    2958    77615827 :                                         seenmax |= cmp == 0;
    2959             :                                 }
    2960  2380449330 :                                 if (minval && !isnil) {
    2961    50573261 :                                         cmp = cmpf(minval, valp);
    2962    50571985 :                                         assert(cmp <= 0);
    2963    50571985 :                                         seenmin |= cmp == 0;
    2964             :                                 }
    2965  2380448054 :                                 if (prev && cmpprv) {
    2966  1188586090 :                                         cmp = cmpf(prev, valp);
    2967  1275181959 :                                         assert(!b->tsorted || cmp <= 0);
    2968  1275181959 :                                         assert(!b->trevsorted || cmp >= 0);
    2969  1275181959 :                                         assert(!b->tkey || cmp != 0);
    2970             :                                 }
    2971  2467043923 :                                 seennil |= isnil;
    2972  2467043923 :                                 if (seennil && !cmpprv &&
    2973     4596680 :                                     maxval == NULL && minval == NULL &&
    2974      157045 :                                     minbound == NULL && maxbound == NULL) {
    2975             :                                         /* we've done all the checking
    2976             :                                          * we can do */
    2977             :                                         break;
    2978             :                                 }
    2979  2466886870 :                                 prev = valp;
    2980             :                         }
    2981             :                 } else {        /* b->tkey && !b->tsorted && !b->trevsorted */
    2982             :                         /* we need to check for uniqueness the hard
    2983             :                          * way (i.e. using a hash table) */
    2984       18965 :                         const char *nme = BBP_physical(b->batCacheid);
    2985       18965 :                         Hash *hs = NULL;
    2986       18965 :                         BUN mask;
    2987             : 
    2988       18965 :                         if ((hs = GDKzalloc(sizeof(Hash))) == NULL) {
    2989           0 :                                 TRC_WARNING(BAT_, "Cannot allocate hash table\n");
    2990           0 :                                 goto abort_check;
    2991             :                         }
    2992       18965 :                         if (snprintf(hs->heaplink.filename, sizeof(hs->heaplink.filename), "%s.thshprpl%x", nme, (unsigned) MT_getpid()) >= (int) sizeof(hs->heaplink.filename) ||
    2993       18966 :                             snprintf(hs->heapbckt.filename, sizeof(hs->heapbckt.filename), "%s.thshprpb%x", nme, (unsigned) MT_getpid()) >= (int) sizeof(hs->heapbckt.filename)) {
    2994             :                                 /* cannot happen, see comment in gdk.h
    2995             :                                  * about sizes near definition of
    2996             :                                  * BBPINIT */
    2997           0 :                                 GDKfree(hs);
    2998           0 :                                 TRC_CRITICAL(BAT_, "Heap filename is too large\n");
    2999           0 :                                 goto abort_check;
    3000             :                         }
    3001       18966 :                         if (ATOMsize(b->ttype) == 1)
    3002             :                                 mask = (BUN) 1 << 8;
    3003       18962 :                         else if (ATOMsize(b->ttype) == 2)
    3004             :                                 mask = (BUN) 1 << 16;
    3005             :                         else
    3006       18962 :                                 mask = HASHmask(b->batCount);
    3007       18966 :                         hs->heapbckt.parentid = b->batCacheid;
    3008       18966 :                         hs->heaplink.parentid = b->batCacheid;
    3009       18966 :                         if ((hs->heaplink.farmid = BBPselectfarm(
    3010       18966 :                                      TRANSIENT, b->ttype, hashheap)) < 0 ||
    3011       18966 :                             (hs->heapbckt.farmid = BBPselectfarm(
    3012       37932 :                                     TRANSIENT, b->ttype, hashheap)) < 0 ||
    3013       18966 :                             HASHnew(hs, b->ttype, BATcount(b),
    3014             :                                     mask, BUN_NONE, false) != GDK_SUCCEED) {
    3015           0 :                                 GDKfree(hs);
    3016           0 :                                 TRC_WARNING(BAT_, "Cannot allocate hash table\n");
    3017           0 :                                 goto abort_check;
    3018             :                         }
    3019    35158043 :                         BATloop(b, p, q) {
    3020    35139080 :                                 BUN hb;
    3021    35139080 :                                 BUN prb;
    3022    35139080 :                                 valp = BUNtail(bi, p);
    3023    35139080 :                                 bool isnil = cmpf(valp, nilp) == 0;
    3024    35139133 :                                 assert(!isnil || !notnull);
    3025    35139133 :                                 assert(b->ttype != TYPE_flt || !isinf(*(flt*)valp));
    3026    35139133 :                                 assert(b->ttype != TYPE_dbl || !isinf(*(dbl*)valp));
    3027    35139133 :                                 if (b->tascii)
    3028       10168 :                                         assert_ascii(valp);
    3029    35139133 :                                 if (minbound && !isnil) {
    3030           0 :                                         cmp = cmpf(minbound, valp);
    3031           0 :                                         assert(cmp <= 0);
    3032             :                                 }
    3033    35139133 :                                 if (maxbound && !isnil) {
    3034           0 :                                         cmp = cmpf(maxbound, valp);
    3035           0 :                                         assert(cmp > 0);
    3036             :                                 }
    3037    35139133 :                                 if (maxval && !isnil) {
    3038        6020 :                                         cmp = cmpf(maxval, valp);
    3039        6020 :                                         assert(cmp >= 0);
    3040        6020 :                                         seenmax |= cmp == 0;
    3041             :                                 }
    3042    35139133 :                                 if (minval && !isnil) {
    3043        6020 :                                         cmp = cmpf(minval, valp);
    3044        6020 :                                         assert(cmp <= 0);
    3045        6020 :                                         seenmin |= cmp == 0;
    3046             :                                 }
    3047    35139133 :                                 prb = HASHprobe(hs, valp);
    3048    35139096 :                                 for (hb = HASHget(hs, prb);
    3049    35747351 :                                      hb != BUN_NONE;
    3050      608255 :                                      hb = HASHgetlink(hs, hb))
    3051      608386 :                                         if (cmpf(valp, BUNtail(bi, hb)) == 0)
    3052           0 :                                                 assert(!b->tkey);
    3053    35138965 :                                 HASHputlink(hs, p, HASHget(hs, prb));
    3054    35138900 :                                 HASHput(hs, prb, p);
    3055    35139077 :                                 assert(!b->tnonil || !isnil);
    3056    35139077 :                                 seennil |= isnil;
    3057             :                         }
    3058       18963 :                         HEAPfree(&hs->heaplink, true);
    3059       18966 :                         HEAPfree(&hs->heapbckt, true);
    3060       18966 :                         GDKfree(hs);
    3061             :                 }
    3062     5956939 :           abort_check:
    3063     5956939 :                 GDKclrerr();
    3064     5957399 :                 assert(maxval == NULL || seenmax);
    3065     5957399 :                 assert(minval == NULL || seenmin);
    3066     5957399 :                 assert(!b->tnil || seennil);
    3067             :         }
    3068     8198213 :         MT_lock_unset(&b->theaplock);
    3069             : }

Generated by: LCOV version 1.14