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 : * @t The Goblin Database Kernel
15 : * @v Version 3.05
16 : * @a Martin L. Kersten, Peter Boncz, Niels Nes, Sjoerd Mullender
17 : *
18 : * @+ The Inner Core
19 : * The innermost library of the MonetDB database system is formed by
20 : * the library called GDK, an abbreviation of Goblin Database Kernel.
21 : * Its development was originally rooted in the design of a pure
22 : * active-object-oriented programming language, before development
23 : * was shifted towards a reusable database kernel engine.
24 : *
25 : * GDK is a C library that provides ACID properties on a DSM model
26 : * @tex
27 : * [@cite{Copeland85}]
28 : * @end tex
29 : * , using main-memory
30 : * database algorithms
31 : * @tex
32 : * [@cite{Garcia-Molina92}]
33 : * @end tex
34 : * built on virtual-memory
35 : * OS primitives and multi-threaded parallelism.
36 : * Its implementation has undergone various changes over its decade
37 : * of development, many of which were driven by external needs to
38 : * obtain a robust and fast database system.
39 : *
40 : * The coding scheme explored in GDK has also laid a foundation to
41 : * communicate over time experiences and to provide (hopefully)
42 : * helpful advice near to the place where the code-reader needs it.
43 : * Of course, over such a long time the documentation diverges from
44 : * reality. Especially in areas where the environment of this package
45 : * is being described.
46 : * Consider such deviations as historic landmarks, e.g. crystallization
47 : * of brave ideas and mistakes rectified at a later stage.
48 : *
49 : * @+ Short Outline
50 : * The facilities provided in this implementation are:
51 : * @itemize
52 : * @item
53 : * GDK or Goblin Database Kernel routines for session management
54 : * @item
55 : * BAT routines that define the primitive operations on the
56 : * database tables (BATs).
57 : * @item
58 : * BBP routines to manage the BAT Buffer Pool (BBP).
59 : * @item
60 : * ATOM routines to manipulate primitive types, define new types
61 : * using an ADT interface.
62 : * @item
63 : * HEAP routines for manipulating heaps: linear spaces of memory
64 : * that are GDK's vehicle of mass storage (on which BATs are built).
65 : * @item
66 : * DELTA routines to access inserted/deleted elements within a
67 : * transaction.
68 : * @item
69 : * HASH routines for manipulating GDK's built-in linear-chained
70 : * hash tables, for accelerating lookup searches on BATs.
71 : * @item
72 : * TM routines that provide basic transaction management primitives.
73 : * @item
74 : * TRG routines that provided active database support. [DEPRECATED]
75 : * @item
76 : * ALIGN routines that implement BAT alignment management.
77 : * @end itemize
78 : *
79 : * The Binary Association Table (BAT) is the lowest level of storage
80 : * considered in the Goblin runtime system
81 : * @tex
82 : * [@cite{Goblin}]
83 : * @end tex
84 : * . A BAT is a
85 : * self-descriptive main-memory structure that represents the
86 : * @strong{binary relationship} between two atomic types. The
87 : * association can be defined over:
88 : * @table @code
89 : * @item void:
90 : * virtual-OIDs: a densely ascending column of OIDs (takes zero-storage).
91 : * @item bit:
92 : * Booleans, implemented as one byte values.
93 : * @item bte:
94 : * Tiny (1-byte) integers (8-bit @strong{integer}s).
95 : * @item sht:
96 : * Short integers (16-bit @strong{integer}s).
97 : * @item int:
98 : * This is the C @strong{int} type (32-bit).
99 : * @item oid:
100 : * Unique @strong{long int} values uses as object identifier. Highest
101 : * bit cleared always. Thus, oids-s are 31-bit numbers on
102 : * 32-bit systems, and 63-bit numbers on 64-bit systems.
103 : * @item ptr:
104 : * Memory pointer values. DEPRECATED. Can only be stored in transient
105 : * BATs.
106 : * @item flt:
107 : * The IEEE @strong{float} type.
108 : * @item dbl:
109 : * The IEEE @strong{double} type.
110 : * @item lng:
111 : * Longs: the C @strong{long long} type (64-bit integers).
112 : * @item hge:
113 : * "huge" integers: the GCC @strong{__int128} type (128-bit integers).
114 : * @item str:
115 : * UTF-8 strings (Unicode). A zero-terminated byte sequence.
116 : * @item bat:
117 : * Bat descriptor. This allows for recursive administered tables, but
118 : * severely complicates transaction management. Therefore, they CAN
119 : * ONLY BE STORED IN TRANSIENT BATs.
120 : * @end table
121 : *
122 : * This model can be used as a back-end model underlying other -higher
123 : * level- models, in order to achieve @strong{better performance} and
124 : * @strong{data independence} in one go. The relational model and the
125 : * object-oriented model can be mapped on BATs by vertically splitting
126 : * every table (or class) for each attribute. Each such a column is
127 : * then stored in a BAT with type @strong{bat[oid,attribute]}, where
128 : * the unique object identifiers link tuples in the different BATs.
129 : * Relationship attributes in the object-oriented model hence are
130 : * mapped to @strong{bat[oid,oid]} tables, being equivalent to the
131 : * concept of @emph{join indexes} @tex [@cite{Valduriez87}] @end tex .
132 : *
133 : * The set of built-in types can be extended with user-defined types
134 : * through an ADT interface. They are linked with the kernel to
135 : * obtain an enhanced library, or they are dynamically loaded upon
136 : * request.
137 : *
138 : * Types can be derived from other types. They represent something
139 : * different than that from which they are derived, but their internal
140 : * storage management is equal. This feature facilitates the work of
141 : * extension programmers, by enabling reuse of implementation code,
142 : * but is also used to keep the GDK code portable from 32-bits to
143 : * 64-bits machines: the @strong{oid} and @strong{ptr} types are
144 : * derived from @strong{int} on 32-bits machines, but is derived from
145 : * @strong{lng} on 64 bits machines. This requires changes in only two
146 : * lines of code each.
147 : *
148 : * To accelerate lookup and search in BATs, GDK supports one built-in
149 : * search accelerator: hash tables. We choose an implementation
150 : * efficient for main-memory: bucket chained hash
151 : * @tex
152 : * [@cite{LehCar86,Analyti92}]
153 : * @end tex
154 : * . Alternatively, when the table is sorted, it will resort to
155 : * merge-scan operations or binary lookups.
156 : *
157 : * BATs are built on the concept of heaps, which are large pieces of
158 : * main memory. They can also consist of virtual memory, in case the
159 : * working set exceeds main-memory. In this case, GDK supports
160 : * operations that cluster the heaps of a BAT, in order to improve
161 : * performance of its main-memory.
162 : *
163 : *
164 : * @- Rationale
165 : * The rationale for choosing a BAT as the building block for both
166 : * relational and object-oriented system is based on the following
167 : * observations:
168 : *
169 : * @itemize
170 : * @item -
171 : * Given the fact that CPU speed and main-memory increase in current
172 : * workstation hardware for the last years has been exceeding IO
173 : * access speed increase, traditional disk-page oriented algorithms do
174 : * no longer take best advantage of hardware, in most database
175 : * operations.
176 : *
177 : * Instead of having a disk-block oriented kernel with a large memory
178 : * cache, we choose to build a main-memory kernel, that only under
179 : * large data volumes slowly degrades to IO-bound performance,
180 : * comparable to traditional systems
181 : * @tex
182 : * [@cite{boncz95,boncz96}]
183 : * @end tex
184 : * .
185 : *
186 : * @item -
187 : * Traditional (disk-based) relational systems move too much data
188 : * around to save on (main-memory) join operations.
189 : *
190 : * The fully decomposed store (DSM
191 : * @tex
192 : * [@cite{Copeland85})]
193 : * @end tex
194 : * assures that only those attributes of a relation that are needed,
195 : * will have to be accessed.
196 : *
197 : * @item -
198 : * The data management issues for a binary association is much
199 : * easier to deal with than traditional @emph{struct}-based approaches
200 : * encountered in relational systems.
201 : *
202 : * @item -
203 : * Object-oriented systems often maintain a double cache, one with the
204 : * disk-based representation and a C pointer-based main-memory
205 : * structure. This causes expensive conversions and replicated
206 : * storage management. GDK does not do such `pointer swizzling'. It
207 : * used virtual-memory (@strong{mmap()}) and buffer management advice
208 : * (@strong{madvise()}) OS primitives to cache only once. Tables take
209 : * the same form in memory as on disk, making the use of this
210 : * technique transparent
211 : * @tex
212 : * [@cite{oo7}]
213 : * @end tex
214 : * .
215 : * @end itemize
216 : *
217 : * A RDBMS or OODBMS based on BATs strongly depends on our ability to
218 : * efficiently support tuples and to handle small joins, respectively.
219 : *
220 : * The remainder of this document describes the Goblin Database kernel
221 : * implementation at greater detail. It is organized as follows:
222 : * @table @code
223 : * @item @strong{GDK Interface}:
224 : *
225 : * It describes the global interface with which GDK sessions can be
226 : * started and ended, and environment variables used.
227 : *
228 : * @item @strong{Binary Association Tables}:
229 : *
230 : * As already mentioned, these are the primary data structure of GDK.
231 : * This chapter describes the kernel operations for creation,
232 : * destruction and basic manipulation of BATs and BUNs (i.e. tuples:
233 : * Binary UNits).
234 : *
235 : * @item @strong{BAT Buffer Pool:}
236 : *
237 : * All BATs are registered in the BAT Buffer Pool. This directory is
238 : * used to guide swapping in and out of BATs. Here we find routines
239 : * that guide this swapping process.
240 : *
241 : * @item @strong{GDK Extensibility:}
242 : *
243 : * Atoms can be defined using a unified ADT interface. There is also
244 : * an interface to extend the GDK library with dynamically linked
245 : * object code.
246 : *
247 : * @item @strong{GDK Utilities:}
248 : *
249 : * Memory allocation and error handling primitives are
250 : * provided. Layers built on top of GDK should use them, for proper
251 : * system monitoring. Thread management is also included here.
252 : *
253 : * @item @strong{Transaction Management:}
254 : *
255 : * For the time being, we just provide BAT-grained concurrency and
256 : * global transactions. Work is needed here.
257 : *
258 : * @item @strong{BAT Alignment:}
259 : * Due to the mapping of multi-ary datamodels onto the BAT model, we
260 : * expect many correspondences among BATs, e.g.
261 : * @emph{bat(oid,attr1),.. bat(oid,attrN)} vertical
262 : * decompositions. Frequent activities will be to jump from one
263 : * attribute to the other (`bunhopping'). If the head columns are
264 : * equal lists in two BATs, merge or even array lookups can be used
265 : * instead of hash lookups. The alignment interface makes these
266 : * relations explicitly manageable.
267 : *
268 : * In GDK, complex data models are mapped with DSM on binary tables.
269 : * Usually, one decomposes @emph{N}-ary relations into @emph{N} BATs
270 : * with an @strong{oid} in the head column, and the attribute in the
271 : * tail column. There may well be groups of tables that have the same
272 : * sets of @strong{oid}s, equally ordered. The alignment interface is
273 : * intended to make this explicit. Implementations can use this
274 : * interface to detect this situation, and use cheaper algorithms
275 : * (like merge-join, or even array lookup) instead.
276 : *
277 : * @item @strong{BAT Iterators:}
278 : *
279 : * Iterators are C macros that generally encapsulate a complex
280 : * for-loop. They would be the equivalent of cursors in the SQL
281 : * model. The macro interface (instead of a function call interface)
282 : * is chosen to achieve speed when iterating main-memory tables.
283 : *
284 : * @item @strong{Common BAT Operations:}
285 : *
286 : * These are much used operations on BATs, such as aggregate functions
287 : * and relational operators. They are implemented in terms of BAT- and
288 : * BUN-manipulation GDK primitives.
289 : * @end table
290 : *
291 : * @+ Interface Files
292 : * In this section we summarize the user interface to the GDK library.
293 : * It consist of a header file (gdk.h) and an object library
294 : * (gdklib.a), which implements the required functionality. The header
295 : * file must be included in any program that uses the library. The
296 : * library must be linked with such a program.
297 : *
298 : * @- Database Context
299 : *
300 : * The MonetDB environment settings are collected in a configuration
301 : * file. Amongst others it contains the location of the database
302 : * directory. First, the database directory is closed for other
303 : * servers running at the same time. Second, performance enhancements
304 : * may take effect, such as locking the code into memory (if the OS
305 : * permits) and preloading the data dictionary. An error at this
306 : * stage normally lead to an abort.
307 : */
308 :
309 : #ifndef _GDK_H_
310 : #define _GDK_H_
311 :
312 : /* standard includes upon which all configure tests depend */
313 : #ifdef HAVE_SYS_TYPES_H
314 : # include <sys/types.h>
315 : #endif
316 : #ifdef HAVE_SYS_STAT_H
317 : # include <sys/stat.h>
318 : #endif
319 : #include <stddef.h>
320 : #include <string.h>
321 : #ifdef HAVE_UNISTD_H
322 : # include <unistd.h>
323 : #endif
324 :
325 : #include <ctype.h> /* isspace etc. */
326 :
327 : #ifdef HAVE_SYS_FILE_H
328 : # include <sys/file.h>
329 : #endif
330 :
331 : #ifdef HAVE_DIRENT_H
332 : # include <dirent.h>
333 : #endif
334 :
335 : #include <limits.h> /* for *_MIN and *_MAX */
336 : #include <float.h> /* for FLT_MAX and DBL_MAX */
337 :
338 : #ifdef WIN32
339 : #ifndef LIBGDK
340 : #define gdk_export extern __declspec(dllimport)
341 : #else
342 : #define gdk_export extern __declspec(dllexport)
343 : #endif
344 : #else
345 : #define gdk_export extern
346 : #endif
347 :
348 : /* Only ever compare with GDK_SUCCEED, never with GDK_FAIL, and do not
349 : * use as a Boolean. */
350 : typedef enum { GDK_FAIL, GDK_SUCCEED } gdk_return;
351 :
352 : gdk_export _Noreturn void GDKfatal(_In_z_ _Printf_format_string_ const char *format, ...)
353 : __attribute__((__format__(__printf__, 1, 2)));
354 :
355 : #include "gdk_system.h"
356 : #include "gdk_posix.h"
357 : #include "stream.h"
358 : #include "mstring.h"
359 :
360 : #undef MIN
361 : #undef MAX
362 : #define MAX(A,B) ((A)<(B)?(B):(A))
363 : #define MIN(A,B) ((A)>(B)?(B):(A))
364 :
365 : /* defines from ctype with casts that allow passing char values */
366 : #define GDKisspace(c) isspace((unsigned char) (c))
367 : #define GDKisalnum(c) isalnum((unsigned char) (c))
368 : #define GDKisdigit(c) isdigit((unsigned char) (c))
369 : #define GDKisxdigit(c) isxdigit((unsigned char) (c))
370 :
371 : #define BATDIR "bat"
372 : #define TEMPDIR_NAME "TEMP_DATA"
373 :
374 : #define DELDIR BATDIR DIR_SEP_STR "DELETE_ME"
375 : #define BAKDIR BATDIR DIR_SEP_STR "BACKUP"
376 : #define SUBDIR BAKDIR DIR_SEP_STR "SUBCOMMIT" /* note K, not T */
377 : #define LEFTDIR BATDIR DIR_SEP_STR "LEFTOVERS"
378 : #define TEMPDIR BATDIR DIR_SEP_STR TEMPDIR_NAME
379 :
380 : /*
381 : See `man mserver5` or tools/mserver/mserver5.1
382 : for a documentation of the following debug options.
383 : */
384 :
385 : #define THRDMASK (1U)
386 : #define CHECKMASK (1U<<1)
387 : #define CHECKDEBUG if (ATOMIC_GET(&GDKdebug) & CHECKMASK)
388 : #define PROPMASK (1U<<3) /* unused */
389 : #define PROPDEBUG if (ATOMIC_GET(&GDKdebug) & PROPMASK) /* unused */
390 : #define IOMASK (1U<<4)
391 : #define BATMASK (1U<<5)
392 : #define PARMASK (1U<<7)
393 : #define TESTINGMASK (1U<<8)
394 : #define TMMASK (1U<<9)
395 : #define TEMMASK (1U<<10)
396 : #define PERFMASK (1U<<12)
397 : #define DELTAMASK (1U<<13)
398 : #define LOADMASK (1U<<14)
399 : #define PUSHCANDMASK (1U<<15) /* used in opt_pushselect.c */
400 : #define TAILCHKMASK (1U<<16) /* check .tail file size during commit */
401 : #define ACCELMASK (1U<<20)
402 : #define ALGOMASK (1U<<21)
403 :
404 : #define NOSYNCMASK (1U<<24)
405 :
406 : #define DEADBEEFMASK (1U<<25)
407 : #define DEADBEEFCHK if (!(ATOMIC_GET(&GDKdebug) & DEADBEEFMASK))
408 :
409 : #define ALLOCMASK (1U<<26)
410 :
411 : /* M5, only; cf.,
412 : * monetdb5/mal/mal.h
413 : */
414 : #define OPTMASK (1U<<27)
415 :
416 : #define HEAPMASK (1U<<28)
417 :
418 : #define FORCEMITOMASK (1U<<29)
419 : #define FORCEMITODEBUG if (ATOMIC_GET(&GDKdebug) & FORCEMITOMASK)
420 :
421 : #ifndef TRUE
422 : #define TRUE true
423 : #define FALSE false
424 : #endif
425 :
426 : #define BATMARGIN 1.2 /* extra free margin for new heaps */
427 : #define BATTINY_BITS 8
428 : #define BATTINY ((BUN)1<<BATTINY_BITS) /* minimum allocation buncnt for a BAT */
429 :
430 : enum {
431 : TYPE_void = 0,
432 : TYPE_msk, /* bit mask */
433 : TYPE_bit, /* TRUE, FALSE, or nil */
434 : TYPE_bte,
435 : TYPE_sht,
436 : TYPE_int,
437 : TYPE_oid,
438 : TYPE_ptr, /* C pointer! */
439 : TYPE_flt,
440 : TYPE_dbl,
441 : TYPE_lng,
442 : #ifdef HAVE_HGE
443 : TYPE_hge,
444 : #endif
445 : TYPE_date,
446 : TYPE_daytime,
447 : TYPE_timestamp,
448 : TYPE_uuid,
449 : TYPE_str,
450 : TYPE_blob,
451 : TYPE_any = 255, /* limit types to <255! */
452 : };
453 :
454 : typedef bool msk;
455 : typedef int8_t bit;
456 : typedef int8_t bte;
457 : typedef int16_t sht;
458 : /* typedef int64_t lng; -- defined in gdk_system.h */
459 : typedef uint64_t ulng;
460 :
461 : #define SIZEOF_OID SIZEOF_SIZE_T
462 : typedef size_t oid;
463 : #define OIDFMT "%zu"
464 :
465 : typedef int bat; /* Index into BBP */
466 : typedef void *ptr; /* Internal coding of types */
467 :
468 : #define SIZEOF_PTR SIZEOF_VOID_P
469 : typedef float flt;
470 : typedef double dbl;
471 : typedef char *str;
472 :
473 : #define UUID_SIZE 16 /* size of a UUID */
474 : #define UUID_STRLEN 36 /* length of string representation */
475 :
476 : typedef union {
477 : #ifdef HAVE_HGE
478 : hge h; /* force alignment, not otherwise used */
479 : #else
480 : lng l[2]; /* force alignment, not otherwise used */
481 : #endif
482 : uint8_t u[UUID_SIZE];
483 : } uuid;
484 :
485 : typedef struct {
486 : size_t nitems;
487 : char data[] __attribute__((__nonstring__));
488 : } blob;
489 : gdk_export size_t blobsize(size_t nitems) __attribute__((__const__));
490 :
491 : #define SIZEOF_LNG 8
492 : #define LL_CONSTANT(val) INT64_C(val)
493 : #define LLFMT "%" PRId64
494 : #define ULLFMT "%" PRIu64
495 : #define LLSCN "%" SCNd64
496 : #define ULLSCN "%" SCNu64
497 :
498 : typedef oid var_t; /* type used for heap index of var-sized BAT */
499 : #define SIZEOF_VAR_T SIZEOF_OID
500 : #define VARFMT OIDFMT
501 :
502 : #if SIZEOF_VAR_T == SIZEOF_INT
503 : #define VAR_MAX ((var_t) INT_MAX)
504 : #else
505 : #define VAR_MAX ((var_t) INT64_MAX)
506 : #endif
507 :
508 : typedef oid BUN; /* BUN position */
509 : #define SIZEOF_BUN SIZEOF_OID
510 : #define BUNFMT OIDFMT
511 : /* alternatively:
512 : typedef size_t BUN;
513 : #define SIZEOF_BUN SIZEOF_SIZE_T
514 : #define BUNFMT "%zu"
515 : */
516 : #if SIZEOF_BUN == SIZEOF_INT
517 : #define BUN_NONE ((BUN) INT_MAX)
518 : #else
519 : #define BUN_NONE ((BUN) INT64_MAX)
520 : #endif
521 : #define BUN_MAX (BUN_NONE - 1) /* maximum allowed size of a BAT */
522 :
523 : /*
524 : * @- Checking and Error definitions:
525 : */
526 : #define ATOMextern(t) (ATOMstorage(t) >= TYPE_str)
527 :
528 : typedef enum {
529 : PERSISTENT = 0,
530 : TRANSIENT,
531 : SYSTRANS,
532 : } role_t;
533 :
534 : /* Heap storage modes */
535 : typedef enum {
536 : STORE_INVALID = 0, /* invalid value, used to indicate error */
537 : STORE_MEM, /* load into GDKmalloced memory */
538 : STORE_MMAP, /* mmap() into virtual memory */
539 : STORE_PRIV, /* BAT copy of copy-on-write mmap */
540 : STORE_CMEM, /* load into malloc (not GDKmalloc) memory*/
541 : STORE_NOWN, /* memory not owned by the BAT */
542 : STORE_MMAPABS, /* mmap() into virtual memory from an
543 : * absolute path (not part of dbfarm) */
544 : } storage_t;
545 :
546 : typedef struct {
547 : size_t free; /* index where free area starts. */
548 : size_t size; /* size of the heap (bytes) */
549 : char *base; /* base pointer in memory. */
550 : #if SIZEOF_VOID_P == 4
551 : char filename[32]; /* file containing image of the heap */
552 : #else
553 : char filename[40]; /* file containing image of the heap */
554 : #endif
555 :
556 : ATOMIC_TYPE refs; /* reference count for this heap */
557 : bte farmid; /* id of farm where heap is located */
558 : bool cleanhash; /* string heaps must clean hash */
559 : bool dirty; /* specific heap dirty marker */
560 : bool remove; /* remove storage file when freeing */
561 : bool wasempty; /* heap was empty when last saved/created */
562 : bool hasfile; /* .filename exists on disk */
563 : storage_t storage; /* storage mode (mmap/malloc). */
564 : storage_t newstorage; /* new desired storage mode at re-allocation. */
565 : bat parentid; /* cache id of VIEW parent bat */
566 : } Heap;
567 :
568 : typedef struct Hash Hash;
569 : typedef struct Imprints Imprints;
570 : typedef struct Strimps Strimps;
571 :
572 : #ifdef HAVE_RTREE
573 : typedef struct RTree RTree;
574 : #endif
575 :
576 : /*
577 : * @+ Binary Association Tables
578 : * Having gone to the previous preliminary definitions, we will now
579 : * introduce the structure of Binary Association Tables (BATs) in
580 : * detail. They are the basic storage unit on which GDK is modeled.
581 : *
582 : * The BAT holds an unlimited number of binary associations, called
583 : * BUNs (@strong{Binary UNits}). The two attributes of a BUN are
584 : * called @strong{head} (left) and @strong{tail} (right) in the
585 : * remainder of this document.
586 : *
587 : * @c image{http://monetdb.cwi.nl/projects/monetdb-mk/imgs/bat1,,,,feps}
588 : *
589 : * The above figure shows what a BAT looks like. It consists of two
590 : * columns, called head and tail, such that we have always binary
591 : * tuples (BUNs). The overlooking structure is the @strong{BAT
592 : * record}. It points to a heap structure called the @strong{BUN
593 : * heap}. This heap contains the atomic values inside the two
594 : * columns. If they are fixed-sized atoms, these atoms reside directly
595 : * in the BUN heap. If they are variable-sized atoms (such as string
596 : * or polygon), however, the columns has an extra heap for storing
597 : * those (such @strong{variable-sized atom heaps} are then referred to
598 : * as @strong{Head Heap}s and @strong{Tail Heap}s). The BUN heap then
599 : * contains integer byte-offsets (fixed-sized, of course) into a head-
600 : * or tail-heap.
601 : *
602 : * The BUN heap contains a contiguous range of BUNs. It starts after
603 : * the @strong{first} pointer, and finishes at the end in the
604 : * @strong{free} area of the BUN. All BUNs after the @strong{inserted}
605 : * pointer have been added in the last transaction (and will be
606 : * deleted on a transaction abort). All BUNs between the
607 : * @strong{deleted} pointer and the @strong{first} have been deleted
608 : * in this transaction (and will be reinserted at a transaction
609 : * abort).
610 : *
611 : * The location of a certain BUN in a BAT may change between
612 : * successive library routine invocations. Therefore, one should
613 : * avoid keeping references into the BAT storage area for long
614 : * periods.
615 : *
616 : * Passing values between the library routines and the enclosing C
617 : * program is primarily through value pointers of type ptr. Pointers
618 : * into the BAT storage area should only be used for retrieval. Direct
619 : * updates of data stored in a BAT is forbidden. The user should
620 : * adhere to the interface conventions to guarantee the integrity
621 : * rules and to maintain the (hidden) auxiliary search structures.
622 : *
623 : * @- GDK variant record type
624 : * When manipulating values, MonetDB puts them into value records.
625 : * The built-in types have a direct entry in the union. Others should
626 : * be represented as a pointer of memory in pval or as a string, which
627 : * is basically the same. In such cases the len field indicates the
628 : * size of this piece of memory.
629 : */
630 : typedef struct {
631 : union { /* storage is first in the record */
632 : int ival;
633 : oid oval;
634 : sht shval;
635 : bte btval;
636 : msk mval;
637 : flt fval;
638 : ptr pval;
639 : bat bval;
640 : str sval;
641 : dbl dval;
642 : lng lval;
643 : #ifdef HAVE_HGE
644 : hge hval;
645 : #endif
646 : uuid uval;
647 : } val;
648 : size_t len;
649 : short vtype;
650 : bool bat;
651 : } *ValPtr, ValRecord;
652 :
653 : /* interface definitions */
654 : gdk_export void *VALconvert(int typ, ValPtr t);
655 : gdk_export char *VALformat(const ValRecord *res)
656 : __attribute__((__warn_unused_result__));
657 : gdk_export ValPtr VALcopy(ValPtr dst, const ValRecord *src);
658 : gdk_export ValPtr VALinit(ValPtr d, int tpe, const void *s);
659 : gdk_export void VALempty(ValPtr v);
660 : gdk_export void VALclear(ValPtr v);
661 : gdk_export ValPtr VALset(ValPtr v, int t, void *p);
662 : gdk_export void *VALget(ValPtr v);
663 : gdk_export int VALcmp(const ValRecord *p, const ValRecord *q);
664 : gdk_export bool VALisnil(const ValRecord *v);
665 :
666 : /*
667 : * @- The BAT record
668 : * The elements of the BAT structure are introduced in the remainder.
669 : * Instead of using the underlying types hidden beneath it, one should
670 : * use a @emph{BAT} type that is supposed to look like this:
671 : * @verbatim
672 : * typedef struct {
673 : * // static BAT properties
674 : * bat batCacheid; // bat id: index in BBPcache
675 : * bool batTransient; // persistence mode
676 : * bool batCopiedtodisk; // BAT is saved on disk?
677 : * // dynamic BAT properties
678 : * int batHeat; // heat of BAT in the BBP
679 : * Heap* batBuns; // Heap where the buns are stored
680 : * // DELTA status
681 : * BUN batInserted; // first inserted BUN
682 : * BUN batCount; // Tuple count
683 : * // Tail properties
684 : * int ttype; // Tail type number
685 : * bool tkey; // tail values are unique
686 : * bool tnonil; // tail has no nils
687 : * bool tsorted; // are tail values currently ordered?
688 : * // Tail storage
689 : * int tloc; // byte-offset in BUN for tail elements
690 : * Heap *theap; // heap for varsized tail values
691 : * Hash *thash; // linear chained hash table on tail
692 : * Imprints *timprints; // column imprints index on tail
693 : * orderidx torderidx; // order oid index on tail
694 : * } BAT;
695 : * @end verbatim
696 : *
697 : * The internal structure of the @strong{BAT} record is in fact much
698 : * more complex, but GDK programmers should refrain of making use of
699 : * that.
700 : *
701 : * Since we don't want to pay cost to keep both views in line with
702 : * each other under BAT updates, we work with shared pieces of memory
703 : * between the two views. An update to one will thus automatically
704 : * update the other. In the same line, we allow @strong{synchronized
705 : * BATs} (BATs with identical head columns, and marked as such in the
706 : * @strong{BAT Alignment} interface) now to be clustered horizontally.
707 : *
708 : * @c image{http://monetdb.cwi.nl/projects/monetdb-mk/imgs/bat2,,,,feps}
709 : */
710 :
711 : typedef struct PROPrec PROPrec;
712 :
713 : /* see also comment near BATassertProps() for more information about
714 : * the properties */
715 : typedef struct {
716 : uint16_t width; /* byte-width of the atom array */
717 : int8_t type; /* type id. */
718 : uint8_t shift; /* log2 of bun width */
719 : bool key:1, /* no duplicate values present */
720 : nonil:1, /* there are no nils in the column */
721 : nil:1, /* there is a nil in the column */
722 : sorted:1, /* column is sorted in ascending order */
723 : revsorted:1, /* column is sorted in descending order */
724 : ascii:1; /* string column is fully ASCII (7 bit) */
725 : BUN nokey[2]; /* positions that prove key==FALSE */
726 : BUN nosorted; /* position that proves sorted==FALSE */
727 : BUN norevsorted; /* position that proves revsorted==FALSE */
728 : BUN minpos, maxpos; /* location of min/max value */
729 : double unique_est; /* estimated number of unique values */
730 : oid seq; /* start of dense sequence */
731 :
732 : Heap *heap; /* space for the column. */
733 : BUN baseoff; /* offset in heap->base (in whole items) */
734 : Heap *vheap; /* space for the varsized data. */
735 : Hash *hash; /* hash table */
736 : #ifdef HAVE_RTREE
737 : RTree *rtree; /* rtree geometric index */
738 : #endif
739 : Imprints *imprints; /* column imprints index */
740 : Heap *orderidx; /* order oid index */
741 : Strimps *strimps; /* string imprint index */
742 :
743 : PROPrec *props; /* list of dynamic properties stored in the bat descriptor */
744 : } COLrec;
745 :
746 : #define ORDERIDXOFF 3
747 :
748 : /* assert that atom width is power of 2, i.e., width == 1<<shift */
749 : #define assert_shift_width(shift,width) assert(((shift) == 0 && (width) == 0) || ((unsigned)1<<(shift)) == (unsigned)(width))
750 :
751 : #define GDKLIBRARY_HASHASH 061044U /* first in Jul2021: hashash bit in string heaps */
752 : #define GDKLIBRARY_HSIZE 061045U /* first in Jan2022: heap "size" values */
753 : #define GDKLIBRARY_JSON 061046U /* first in Sep2022: json storage changes*/
754 : #define GDKLIBRARY_STATUS 061047U /* first in Dec2023: no status/filename columns */
755 : #define GDKLIBRARY 061050U /* first in Aug2024 */
756 :
757 : /* The batRestricted field indicates whether a BAT is readonly.
758 : * we have modes: BAT_WRITE = all permitted
759 : * BAT_APPEND = append-only
760 : * BAT_READ = read-only
761 : * VIEW bats are always mapped read-only.
762 : */
763 : typedef enum {
764 : BAT_WRITE, /* all kinds of access allowed */
765 : BAT_READ, /* only read-access allowed */
766 : BAT_APPEND, /* only reads and appends allowed */
767 : } restrict_t;
768 :
769 : /* theaplock: this lock should be held when reading or writing any of
770 : * the fields that are saved in the BBP.dir file (plus any, if any, that
771 : * share bitfields with any of the fields), i.e. hseqbase,
772 : * batRestricted, batTransient, batCount, and the theap properties tkey,
773 : * tseqbase, tsorted, trevsorted, twidth, tshift, tnonil, tnil, tnokey,
774 : * tnosorted, tnorevsorted, tminpos, tmaxpos, and tunique_est, also when
775 : * BBP_logical(bid) is changed, and also when reading or writing any of
776 : * the following fields: theap, tvheap, batInserted, batCapacity. There
777 : * is no need for the lock if the bat cannot possibly be modified
778 : * concurrently, e.g. when it is new and not yet returned to the
779 : * interpreter or during system initialization.
780 : * If multiple bats need to be locked at the same time by the same
781 : * thread, first lock the view, then the view's parent(s). */
782 : typedef struct BAT {
783 : /* static bat properties */
784 : oid hseqbase; /* head seq base */
785 : MT_Id creator_tid; /* which thread created it */
786 : bat batCacheid; /* index into BBP */
787 : role_t batRole; /* role of the bat */
788 :
789 : /* dynamic bat properties */
790 : restrict_t batRestricted:2; /* access privileges */
791 : bool
792 : batTransient:1, /* should the BAT persist on disk? */
793 : batCopiedtodisk:1; /* once written */
794 : uint16_t selcnt; /* how often used in equi select without hash */
795 : uint16_t unused; /* value=0 for now (sneakily used by mat.c) */
796 :
797 : /* delta status administration */
798 : BUN batInserted; /* start of inserted elements */
799 : BUN batCount; /* tuple count */
800 : BUN batCapacity; /* tuple capacity */
801 :
802 : /* dynamic column properties */
803 : COLrec T; /* column info */
804 : MT_Lock theaplock; /* lock protecting heap reference changes */
805 : MT_RWLock thashlock; /* lock specifically for hash management */
806 : MT_Lock batIdxLock; /* lock to manipulate other indexes/properties */
807 : Heap *oldtail; /* old tail heap, to be destroyed after commit */
808 : } BAT;
809 :
810 : /* macros to hide complexity of the BAT structure */
811 : #define ttype T.type
812 : #define tkey T.key
813 : #define tseqbase T.seq
814 : #define tsorted T.sorted
815 : #define trevsorted T.revsorted
816 : #define tascii T.ascii
817 : #define torderidx T.orderidx
818 : #define twidth T.width
819 : #define tshift T.shift
820 : #define tnonil T.nonil
821 : #define tnil T.nil
822 : #define tnokey T.nokey
823 : #define tnosorted T.nosorted
824 : #define tnorevsorted T.norevsorted
825 : #define tminpos T.minpos
826 : #define tmaxpos T.maxpos
827 : #define tunique_est T.unique_est
828 : #define theap T.heap
829 : #define tbaseoff T.baseoff
830 : #define tvheap T.vheap
831 : #define thash T.hash
832 : #define timprints T.imprints
833 : #define tprops T.props
834 : #define tstrimps T.strimps
835 : #ifdef HAVE_RTREE
836 : #define trtree T.rtree
837 : #endif
838 :
839 : /* some access functions for the bitmask type */
840 : static inline void
841 134 : mskSet(BAT *b, BUN p)
842 : {
843 134 : ((uint32_t *) b->theap->base)[p / 32] |= 1U << (p % 32);
844 134 : }
845 :
846 : static inline void
847 7877 : mskClr(BAT *b, BUN p)
848 : {
849 7877 : ((uint32_t *) b->theap->base)[p / 32] &= ~(1U << (p % 32));
850 7877 : }
851 :
852 : static inline void
853 8011 : mskSetVal(BAT *b, BUN p, msk v)
854 : {
855 8011 : if (v)
856 134 : mskSet(b, p);
857 : else
858 7877 : mskClr(b, p);
859 8011 : }
860 :
861 : static inline msk
862 0 : mskGetVal(BAT *b, BUN p)
863 : {
864 0 : return ((uint32_t *) b->theap->base)[p / 32] & (1U << (p % 32));
865 : }
866 :
867 : /*
868 : * @- Heap Management
869 : * Heaps are the low-level entities of mass storage in
870 : * BATs. Currently, they can either be stored on disk, loaded into
871 : * memory, or memory mapped.
872 : * @multitable @columnfractions 0.08 0.7
873 : * @item int
874 : * @tab
875 : * HEAPalloc (Heap *h, size_t nitems, size_t itemsize);
876 : * @item int
877 : * @tab
878 : * HEAPfree (Heap *h, bool remove);
879 : * @item int
880 : * @tab
881 : * HEAPextend (Heap *h, size_t size, bool mayshare);
882 : * @item int
883 : * @tab
884 : * HEAPload (Heap *h, str nme,ext, bool trunc);
885 : * @item int
886 : * @tab
887 : * HEAPsave (Heap *h, str nme,ext, bool dosync);
888 : * @item int
889 : * @tab
890 : * HEAPcopy (Heap *dst,*src);
891 : * @end multitable
892 : *
893 : *
894 : * These routines should be used to alloc free or extend heaps; they
895 : * isolate you from the different ways heaps can be accessed.
896 : */
897 : gdk_export gdk_return HEAPextend(Heap *h, size_t size, bool mayshare)
898 : __attribute__((__warn_unused_result__));
899 : gdk_export size_t HEAPvmsize(Heap *h);
900 : gdk_export size_t HEAPmemsize(Heap *h);
901 : gdk_export void HEAPdecref(Heap *h, bool remove);
902 : gdk_export void HEAPincref(Heap *h);
903 :
904 : #define VIEWtparent(x) ((x)->theap == NULL || (x)->theap->parentid == (x)->batCacheid ? 0 : (x)->theap->parentid)
905 : #define VIEWvtparent(x) ((x)->tvheap == NULL || (x)->tvheap->parentid == (x)->batCacheid ? 0 : (x)->tvheap->parentid)
906 :
907 : #define isVIEW(x) (VIEWtparent(x) != 0 || VIEWvtparent(x) != 0)
908 :
909 : /*
910 : * @+ BAT Buffer Pool
911 : * @multitable @columnfractions 0.08 0.7
912 : * @item int
913 : * @tab BBPfix (bat bi)
914 : * @item int
915 : * @tab BBPunfix (bat bi)
916 : * @item int
917 : * @tab BBPretain (bat bi)
918 : * @item int
919 : * @tab BBPrelease (bat bi)
920 : * @item bat
921 : * @tab BBPindex (str nme)
922 : * @item BAT*
923 : * @tab BATdescriptor (bat bi)
924 : * @end multitable
925 : *
926 : * The BAT Buffer Pool module contains the code to manage the storage
927 : * location of BATs.
928 : *
929 : * The remaining BBP tables contain status information to load, swap
930 : * and migrate the BATs. The core table is BBPcache which contains a
931 : * pointer to the BAT descriptor with its heaps. A zero entry means
932 : * that the file resides on disk. Otherwise it has been read or mapped
933 : * into memory.
934 : *
935 : * BATs loaded into memory are retained in a BAT buffer pool. They
936 : * retain their position within the cache during their life cycle,
937 : * which make indexing BATs a stable operation.
938 : *
939 : * The BBPindex routine checks if a BAT with a certain name is
940 : * registered in the buffer pools. If so, it returns its BAT id. The
941 : * BATdescriptor routine has a BAT id parameter, and returns a pointer
942 : * to the corresponding BAT record (after incrementing the reference
943 : * count). The BAT will be loaded into memory, if necessary.
944 : *
945 : * The structure of the BBP file obeys the tuple format for GDK.
946 : *
947 : * The status and BAT persistency information is encoded in the status
948 : * field.
949 : */
950 : typedef struct {
951 : char *logical; /* logical name (may point at bak) */
952 : char bak[16]; /* logical name backup (tmp_%o) */
953 : BAT descr; /* the BAT descriptor */
954 : char *options; /* A string list of options */
955 : #if SIZEOF_VOID_P == 4
956 : char physical[20]; /* dir + basename for storage */
957 : #else
958 : char physical[24]; /* dir + basename for storage */
959 : #endif
960 : bat next; /* next BBP slot in linked list */
961 : int refs; /* in-memory references on which the loaded status of a BAT relies */
962 : int lrefs; /* logical references on which the existence of a BAT relies */
963 : ATOMIC_TYPE status; /* status mask used for spin locking */
964 : MT_Id pid; /* creator of this bat while "private" */
965 : } BBPrec;
966 :
967 : gdk_export bat BBPlimit;
968 : #if SIZEOF_VOID_P == 4
969 : #define N_BBPINIT 1000
970 : #define BBPINITLOG 11
971 : #else
972 : #define N_BBPINIT 10000
973 : #define BBPINITLOG 14
974 : #endif
975 : #define BBPINIT (1 << BBPINITLOG)
976 : /* absolute maximum number of BATs is N_BBPINIT * BBPINIT
977 : * this also gives the longest possible "physical" name and "bak" name
978 : * of a BAT: the "bak" name is "tmp_%o", so at most 14 + \0 bytes on 64
979 : * bit architecture and 11 + \0 on 32 bit architecture; the physical
980 : * name is a bit more complicated, but the longest possible name is 22 +
981 : * \0 bytes (16 + \0 on 32 bits), the longest possible extension adds
982 : * another 17 bytes (.thsh(grp|uni)(l|b)%08x) */
983 : gdk_export BBPrec *BBP[N_BBPINIT];
984 :
985 : /* fast defines without checks; internal use only */
986 : #define BBP_record(i) BBP[(i)>>BBPINITLOG][(i)&(BBPINIT-1)]
987 : #define BBP_logical(i) BBP_record(i).logical
988 : #define BBP_bak(i) BBP_record(i).bak
989 : #define BBP_next(i) BBP_record(i).next
990 : #define BBP_physical(i) BBP_record(i).physical
991 : #define BBP_options(i) BBP_record(i).options
992 : #define BBP_desc(i) (&BBP_record(i).descr)
993 : #define BBP_refs(i) BBP_record(i).refs
994 : #define BBP_lrefs(i) BBP_record(i).lrefs
995 : #define BBP_status(i) ((unsigned) ATOMIC_GET(&BBP_record(i).status))
996 : #define BBP_pid(i) BBP_record(i).pid
997 : #define BATgetId(b) BBP_logical((b)->batCacheid)
998 : #define BBPvalid(i) (BBP_logical(i) != NULL)
999 :
1000 : #define BBPRENAME_ALREADY (-1)
1001 : #define BBPRENAME_ILLEGAL (-2)
1002 : #define BBPRENAME_LONG (-3)
1003 : #define BBPRENAME_MEMORY (-4)
1004 :
1005 : gdk_export void BBPlock(void);
1006 : gdk_export void BBPunlock(void);
1007 : gdk_export void BBPtmlock(void);
1008 : gdk_export void BBPtmunlock(void);
1009 :
1010 : gdk_export BAT *BBPquickdesc(bat b);
1011 :
1012 : /* BAT iterator, also protects use of BAT heaps with reference counts.
1013 : *
1014 : * A BAT iterator has to be used with caution, but it does have to be
1015 : * used in many place.
1016 : *
1017 : * An iterator is initialized by assigning it the result of a call to
1018 : * either bat_iterator or bat_iterator_nolock. The former must be
1019 : * accompanied by a call to bat_iterator_end to release resources.
1020 : *
1021 : * bat_iterator should be used for BATs that could possibly be modified
1022 : * in another thread while we're reading the contents of the BAT.
1023 : * Alternatively, but only for very quick access, the theaplock can be
1024 : * taken, the data read, and the lock released. For longer duration
1025 : * accesses, it is better to use the iterator, even without the BUNt*
1026 : * macros, since the theaplock is only held very briefly.
1027 : *
1028 : * Note, bat_iterator must only be used for read-only access.
1029 : *
1030 : * If BATs are to be modified, higher level code must assure that no
1031 : * other thread is going to modify the same BAT at the same time. A
1032 : * to-be-modified BAT should not use bat_iterator. It can use
1033 : * bat_iterator_nolock, but be aware that this creates a copy of the
1034 : * heap pointer(s) (i.e. theap and tvheap) and if the heaps get
1035 : * extended, the pointers in the BAT structure may be modified, but that
1036 : * does not modify the pointers in the iterator. This means that after
1037 : * operations that may grow a heap, the iterator should be
1038 : * reinitialized.
1039 : *
1040 : * The BAT iterator provides a number of fields that can (and often
1041 : * should) be used to access information about the BAT. For string
1042 : * BATs, if a parallel threads adds values, the offset heap (theap) may
1043 : * get replaced by one that is wider. This involves changing the twidth
1044 : * and tshift values in the BAT structure. These changed values should
1045 : * not be used to access the data in the iterator. Instead, use the
1046 : * width and shift values in the iterator itself.
1047 : */
1048 : typedef struct BATiter {
1049 : BAT *b;
1050 : Heap *h;
1051 : void *base;
1052 : Heap *vh;
1053 : BUN count;
1054 : BUN baseoff;
1055 : oid tseq;
1056 : BUN hfree, vhfree;
1057 : BUN nokey[2];
1058 : BUN nosorted, norevsorted;
1059 : BUN minpos, maxpos;
1060 : double unique_est;
1061 : uint16_t width;
1062 : uint8_t shift;
1063 : int8_t type;
1064 : bool key:1,
1065 : nonil:1,
1066 : nil:1,
1067 : sorted:1,
1068 : revsorted:1,
1069 : hdirty:1,
1070 : vhdirty:1,
1071 : copiedtodisk:1,
1072 : transient:1,
1073 : ascii:1;
1074 : restrict_t restricted:2;
1075 : #ifndef NDEBUG
1076 : bool locked:1;
1077 : #endif
1078 : union {
1079 : oid tvid;
1080 : bool tmsk;
1081 : };
1082 : } BATiter;
1083 :
1084 : static inline BATiter
1085 116582805 : bat_iterator_nolock(BAT *b)
1086 : {
1087 : /* does not get matched by bat_iterator_end */
1088 116582805 : if (b) {
1089 116582805 : const bool isview = VIEWtparent(b) != 0;
1090 233165610 : return (BATiter) {
1091 : .b = b,
1092 : .h = b->theap,
1093 116582805 : .base = b->theap->base ? b->theap->base + (b->tbaseoff << b->tshift) : NULL,
1094 116582805 : .baseoff = b->tbaseoff,
1095 116582805 : .vh = b->tvheap,
1096 116582805 : .count = b->batCount,
1097 116582805 : .width = b->twidth,
1098 116582805 : .shift = b->tshift,
1099 : .type = b->ttype,
1100 116582805 : .tseq = b->tseqbase,
1101 : /* don't use b->theap->free in case b is a slice */
1102 116582805 : .hfree = b->ttype ?
1103 : b->ttype == TYPE_msk ?
1104 114835254 : (((size_t) b->batCount + 31) / 32) * 4 :
1105 230795101 : (size_t) b->batCount << b->tshift :
1106 : 0,
1107 116582805 : .vhfree = b->tvheap ? b->tvheap->free : 0,
1108 116582805 : .nokey[0] = b->tnokey[0],
1109 116582805 : .nokey[1] = b->tnokey[1],
1110 116582805 : .nosorted = b->tnosorted,
1111 116582805 : .norevsorted = b->tnorevsorted,
1112 116582805 : .minpos = isview ? BUN_NONE : b->tminpos,
1113 102668818 : .maxpos = isview ? BUN_NONE : b->tmaxpos,
1114 116582805 : .unique_est = b->tunique_est,
1115 116582805 : .key = b->tkey,
1116 116582805 : .nonil = b->tnonil,
1117 116582805 : .nil = b->tnil,
1118 116582805 : .sorted = b->tsorted,
1119 116582805 : .revsorted = b->trevsorted,
1120 116582805 : .ascii = b->tascii,
1121 : /* only look at heap dirty flag if we own it */
1122 116582805 : .hdirty = b->theap->parentid == b->batCacheid && b->theap->dirty,
1123 : /* also, if there is no vheap, it's not dirty */
1124 116582805 : .vhdirty = b->tvheap && b->tvheap->parentid == b->batCacheid && b->tvheap->dirty,
1125 116582805 : .copiedtodisk = b->batCopiedtodisk,
1126 116582805 : .transient = b->batTransient,
1127 116582805 : .restricted = b->batRestricted,
1128 : #ifndef NDEBUG
1129 : .locked = false,
1130 : #endif
1131 : };
1132 : }
1133 0 : return (BATiter) {0};
1134 : }
1135 :
1136 : static inline void
1137 35304013 : bat_iterator_incref(BATiter *bi)
1138 : {
1139 : #ifndef NDEBUG
1140 35304013 : bi->locked = true;
1141 : #endif
1142 35304013 : HEAPincref(bi->h);
1143 35306306 : if (bi->vh)
1144 7839359 : HEAPincref(bi->vh);
1145 35306356 : }
1146 :
1147 : static inline BATiter
1148 34309290 : bat_iterator(BAT *b)
1149 : {
1150 : /* needs matching bat_iterator_end */
1151 34309290 : BATiter bi;
1152 34309290 : if (b) {
1153 32502206 : BAT *pb = NULL, *pvb = NULL;
1154 : /* for a view, always first lock the view and then the
1155 : * parent(s)
1156 : * note that a varsized bat can have two different
1157 : * parents and that the parent for the tail can itself
1158 : * have a parent for its vheap (which would have to be
1159 : * our own vheap parent), so lock the vheap after the
1160 : * tail */
1161 32502206 : MT_lock_set(&b->theaplock);
1162 32499241 : if (b->theap->parentid != b->batCacheid) {
1163 9360938 : pb = BBP_desc(b->theap->parentid);
1164 9360938 : MT_lock_set(&pb->theaplock);
1165 : }
1166 32499422 : if (b->tvheap &&
1167 7149634 : b->tvheap->parentid != b->batCacheid &&
1168 2323351 : b->tvheap->parentid != b->theap->parentid) {
1169 175186 : pvb = BBP_desc(b->tvheap->parentid);
1170 175186 : MT_lock_set(&pvb->theaplock);
1171 : }
1172 32499426 : bi = bat_iterator_nolock(b);
1173 32499426 : bat_iterator_incref(&bi);
1174 32503687 : if (pvb)
1175 175192 : MT_lock_unset(&pvb->theaplock);
1176 32505459 : if (pb)
1177 9362787 : MT_lock_unset(&pb->theaplock);
1178 32504539 : MT_lock_unset(&b->theaplock);
1179 : } else {
1180 1807084 : bi = (BATiter) {
1181 : .b = NULL,
1182 : #ifndef NDEBUG
1183 : .locked = true,
1184 : #endif
1185 : };
1186 : }
1187 34308801 : return bi;
1188 : }
1189 :
1190 : /* return a copy of a BATiter instance; needs to be released with
1191 : * bat_iterator_end */
1192 : static inline BATiter
1193 48482 : bat_iterator_copy(BATiter *bip)
1194 : {
1195 48482 : assert(bip);
1196 48482 : assert(bip->locked);
1197 48482 : if (bip->h)
1198 48482 : HEAPincref(bip->h);
1199 48482 : if (bip->vh)
1200 17263 : HEAPincref(bip->vh);
1201 48482 : return *bip;
1202 : }
1203 :
1204 : static inline void
1205 37159547 : bat_iterator_end(BATiter *bip)
1206 : {
1207 : /* matches bat_iterator */
1208 37159547 : assert(bip);
1209 37159547 : assert(bip->locked);
1210 37159547 : if (bip->h)
1211 35352326 : HEAPdecref(bip->h, false);
1212 37159356 : if (bip->vh)
1213 7856606 : HEAPdecref(bip->vh, false);
1214 37159426 : *bip = (BATiter) {0};
1215 37159426 : }
1216 :
1217 : /*
1218 : * @- Internal HEAP Chunk Management
1219 : * Heaps are used in BATs to store data for variable-size atoms. The
1220 : * implementer must manage malloc()/free() functionality for atoms in
1221 : * this heap. A standard implementation is provided here.
1222 : *
1223 : * @table @code
1224 : * @item void
1225 : * HEAP_initialize (Heap* h, size_t nbytes, size_t nprivate, int align )
1226 : * @item void
1227 : * HEAP_destroy (Heap* h)
1228 : * @item var_t
1229 : * HEAP_malloc (Heap* heap, size_t nbytes)
1230 : * @item void
1231 : * HEAP_free (Heap *heap, var_t block)
1232 : * @item int
1233 : * HEAP_private (Heap* h)
1234 : * @item void
1235 : * HEAP_printstatus (Heap* h)
1236 : * @end table
1237 : *
1238 : * The heap space starts with a private space that is left untouched
1239 : * by the normal chunk allocation. You can use this private space
1240 : * e.g. to store the root of an rtree HEAP_malloc allocates a chunk of
1241 : * memory on the heap, and returns an index to it. HEAP_free frees a
1242 : * previously allocated chunk HEAP_private returns an integer index to
1243 : * private space.
1244 : */
1245 :
1246 : gdk_export gdk_return HEAP_initialize(
1247 : Heap *heap, /* nbytes -- Initial size of the heap. */
1248 : size_t nbytes, /* alignment -- for objects on the heap. */
1249 : size_t nprivate, /* nprivate -- Size of private space */
1250 : int alignment /* alignment restriction for allocated chunks */
1251 : );
1252 :
1253 : gdk_export var_t HEAP_malloc(BAT *b, size_t nbytes);
1254 : gdk_export void HEAP_free(Heap *heap, var_t block);
1255 :
1256 : /*
1257 : * @- BAT construction
1258 : * @multitable @columnfractions 0.08 0.7
1259 : * @item @code{BAT* }
1260 : * @tab COLnew (oid headseq, int tailtype, BUN cap, role_t role)
1261 : * @item @code{BAT* }
1262 : * @tab BATextend (BAT *b, BUN newcap)
1263 : * @end multitable
1264 : *
1265 : * A temporary BAT is instantiated using COLnew with the type aliases
1266 : * of the required binary association. The aliases include the
1267 : * built-in types, such as TYPE_int....TYPE_ptr, and the atomic types
1268 : * introduced by the user. The initial capacity to be accommodated
1269 : * within a BAT is indicated by cap. Their extend is automatically
1270 : * incremented upon storage overflow. Failure to create the BAT
1271 : * results in a NULL pointer.
1272 : *
1273 : * The routine BATclone creates an empty BAT storage area with the
1274 : * properties inherited from its argument.
1275 : */
1276 : gdk_export BAT *COLnew(oid hseq, int tltype, BUN capacity, role_t role)
1277 : __attribute__((__warn_unused_result__));
1278 : gdk_export BAT *COLnew2(oid hseq, int tt, BUN cap, role_t role, uint16_t width)
1279 : __attribute__((__warn_unused_result__));
1280 : gdk_export BAT *BATdense(oid hseq, oid tseq, BUN cnt)
1281 : __attribute__((__warn_unused_result__));
1282 : gdk_export gdk_return BATextend(BAT *b, BUN newcap)
1283 : __attribute__((__warn_unused_result__));
1284 :
1285 : /* internal */
1286 : gdk_export uint8_t ATOMelmshift(int sz)
1287 : __attribute__((__const__));
1288 : gdk_export gdk_return ATOMheap(int id, Heap *hp, size_t cap)
1289 : __attribute__((__warn_unused_result__));
1290 : gdk_export const char *BATtailname(const BAT *b);
1291 :
1292 : gdk_export gdk_return GDKupgradevarheap(BAT *b, var_t v, BUN cap, BUN ncopy)
1293 : __attribute__((__warn_unused_result__));
1294 : gdk_export gdk_return BUNappend(BAT *b, const void *right, bool force)
1295 : __attribute__((__warn_unused_result__));
1296 : gdk_export gdk_return BUNappendmulti(BAT *b, const void *values, BUN count, bool force)
1297 : __attribute__((__warn_unused_result__));
1298 : gdk_export gdk_return BATappend(BAT *b, BAT *n, BAT *s, bool force)
1299 : __attribute__((__warn_unused_result__));
1300 :
1301 : gdk_export gdk_return BUNreplace(BAT *b, oid left, const void *right, bool force)
1302 : __attribute__((__warn_unused_result__));
1303 : gdk_export gdk_return BUNreplacemulti(BAT *b, const oid *positions, const void *values, BUN count, bool force)
1304 : __attribute__((__warn_unused_result__));
1305 : gdk_export gdk_return BUNreplacemultiincr(BAT *b, oid position, const void *values, BUN count, bool force)
1306 : __attribute__((__warn_unused_result__));
1307 :
1308 : gdk_export gdk_return BUNdelete(BAT *b, oid o)
1309 : __attribute__((__warn_unused_result__));
1310 : gdk_export gdk_return BATdel(BAT *b, BAT *d)
1311 : __attribute__((__warn_unused_result__));
1312 :
1313 : gdk_export gdk_return BATreplace(BAT *b, BAT *p, BAT *n, bool force)
1314 : __attribute__((__warn_unused_result__));
1315 : gdk_export gdk_return BATupdate(BAT *b, BAT *p, BAT *n, bool force)
1316 : __attribute__((__warn_unused_result__));
1317 : gdk_export gdk_return BATupdatepos(BAT *b, const oid *positions, BAT *n, bool autoincr, bool force)
1318 : __attribute__((__warn_unused_result__));
1319 :
1320 : /* Functions to perform a binary search on a sorted BAT.
1321 : * See gdk_search.c for details. */
1322 : gdk_export BUN SORTfnd(BAT *b, const void *v);
1323 : gdk_export BUN SORTfndfirst(BAT *b, const void *v);
1324 : gdk_export BUN SORTfndlast(BAT *b, const void *v);
1325 :
1326 : gdk_export BUN ORDERfnd(BAT *b, Heap *oidxh, const void *v);
1327 : gdk_export BUN ORDERfndfirst(BAT *b, Heap *oidxh, const void *v);
1328 : gdk_export BUN ORDERfndlast(BAT *b, Heap *oidxh, const void *v);
1329 :
1330 : gdk_export BUN BUNfnd(BAT *b, const void *right);
1331 :
1332 : #define BUNfndVOID(b, v) \
1333 : (((is_oid_nil(*(const oid*)(v)) ^ is_oid_nil((b)->tseqbase)) | \
1334 : (*(const oid*)(v) < (b)->tseqbase) | \
1335 : (*(const oid*)(v) >= (b)->tseqbase + (b)->batCount)) ? \
1336 : BUN_NONE : \
1337 : (BUN) (*(const oid*)(v) - (b)->tseqbase))
1338 :
1339 : #define BATttype(b) (BATtdense(b) ? TYPE_oid : (b)->ttype)
1340 :
1341 : #define tailsize(b,p) ((b)->ttype ? \
1342 : (ATOMstorage((b)->ttype) == TYPE_msk ? \
1343 : (((size_t) (p) + 31) / 32) * 4 : \
1344 : ((size_t) (p)) << (b)->tshift) : \
1345 : 0)
1346 :
1347 : #define Tloc(b,p) ((void *)((b)->theap->base+(((size_t)(p)+(b)->tbaseoff)<<(b)->tshift)))
1348 :
1349 : typedef var_t stridx_t;
1350 : #define SIZEOF_STRIDX_T SIZEOF_VAR_T
1351 : #define GDK_VARALIGN SIZEOF_STRIDX_T
1352 :
1353 : #define BUNtvaroff(bi,p) VarHeapVal((bi).base, (p), (bi).width)
1354 :
1355 : #define BUNtmsk(bi,p) Tmsk(&(bi), (p))
1356 : #define BUNtloc(bi,p) (assert((bi).type != TYPE_msk), ((void *) ((char *) (bi).base + ((p) << (bi).shift))))
1357 : #define BUNtpos(bi,p) Tpos(&(bi),p)
1358 : #define BUNtvar(bi,p) (assert((bi).type && (bi).vh), (void *) ((bi).vh->base+BUNtvaroff(bi,p)))
1359 : #define BUNtail(bi,p) ((bi).type?(bi).vh?BUNtvar(bi,p):(bi).type==TYPE_msk?BUNtmsk(bi,p):BUNtloc(bi,p):BUNtpos(bi,p))
1360 :
1361 : #define BATcount(b) ((b)->batCount)
1362 :
1363 : #include "gdk_atoms.h"
1364 :
1365 : #include "gdk_cand.h"
1366 :
1367 : /*
1368 : * @- BAT properties
1369 : * @multitable @columnfractions 0.08 0.7
1370 : * @item BUN
1371 : * @tab BATcount (BAT *b)
1372 : * @item void
1373 : * @tab BATsetcapacity (BAT *b, BUN cnt)
1374 : * @item void
1375 : * @tab BATsetcount (BAT *b, BUN cnt)
1376 : * @item BAT *
1377 : * @tab BATkey (BAT *b, bool onoff)
1378 : * @item BAT *
1379 : * @tab BATmode (BAT *b, bool transient)
1380 : * @item BAT *
1381 : * @tab BATsetaccess (BAT *b, restrict_t mode)
1382 : * @item int
1383 : * @tab BATdirty (BAT *b)
1384 : * @item restrict_t
1385 : * @tab BATgetaccess (BAT *b)
1386 : * @end multitable
1387 : *
1388 : * The function BATcount returns the number of associations stored in
1389 : * the BAT.
1390 : *
1391 : * The BAT is given a new logical name using BBPrename.
1392 : *
1393 : * The integrity properties to be maintained for the BAT are
1394 : * controlled separately. A key property indicates that duplicates in
1395 : * the association dimension are not permitted.
1396 : *
1397 : * The persistency indicator tells the retention period of BATs. The
1398 : * system support two modes: PERSISTENT and TRANSIENT.
1399 : * The PERSISTENT BATs are automatically saved upon session boundary
1400 : * or transaction commit. TRANSIENT BATs are removed upon transaction
1401 : * boundary. All BATs are initially TRANSIENT unless their mode is
1402 : * changed using the routine BATmode.
1403 : *
1404 : * The BAT properties may be changed at any time using BATkey
1405 : * and BATmode.
1406 : *
1407 : * Valid BAT access properties can be set with BATsetaccess and
1408 : * BATgetaccess: BAT_READ, BAT_APPEND, and BAT_WRITE. BATs can be
1409 : * designated to be read-only. In this case some memory optimizations
1410 : * may be made (slice and fragment bats can point to stable subsets of
1411 : * a parent bat). A special mode is append-only. It is then allowed
1412 : * to insert BUNs at the end of the BAT, but not to modify anything
1413 : * that already was in there.
1414 : */
1415 : gdk_export BUN BATcount_no_nil(BAT *b, BAT *s);
1416 : gdk_export void BATsetcapacity(BAT *b, BUN cnt);
1417 : gdk_export void BATsetcount(BAT *b, BUN cnt);
1418 : gdk_export BUN BATgrows(BAT *b);
1419 : gdk_export gdk_return BATkey(BAT *b, bool onoff);
1420 : gdk_export gdk_return BATmode(BAT *b, bool transient);
1421 : gdk_export void BAThseqbase(BAT *b, oid o);
1422 : gdk_export void BATtseqbase(BAT *b, oid o);
1423 :
1424 : gdk_export BAT *BATsetaccess(BAT *b, restrict_t mode)
1425 : __attribute__((__warn_unused_result__));
1426 : gdk_export restrict_t BATgetaccess(BAT *b);
1427 :
1428 :
1429 : #define BATdirty(b) (!(b)->batCopiedtodisk || \
1430 : (b)->theap->dirty || \
1431 : ((b)->tvheap != NULL && (b)->tvheap->dirty))
1432 : #define BATdirtybi(bi) (!(bi).copiedtodisk || (bi).hdirty || (bi).vhdirty)
1433 :
1434 : #define BATcapacity(b) (b)->batCapacity
1435 : /*
1436 : * @- BAT manipulation
1437 : * @multitable @columnfractions 0.08 0.7
1438 : * @item BAT *
1439 : * @tab BATclear (BAT *b, bool force)
1440 : * @item BAT *
1441 : * @tab COLcopy (BAT *b, int tt, bool writeable, role_t role)
1442 : * @end multitable
1443 : *
1444 : * The routine BATclear removes the binary associations, leading to an
1445 : * empty, but (re-)initialized BAT. Its properties are retained. A
1446 : * temporary copy is obtained with Colcopy. The new BAT has an unique
1447 : * name.
1448 : */
1449 : gdk_export gdk_return BATclear(BAT *b, bool force);
1450 : gdk_export BAT *COLcopy(BAT *b, int tt, bool writable, role_t role);
1451 :
1452 : gdk_export gdk_return BATgroup(BAT **groups, BAT **extents, BAT **histo, BAT *b, BAT *s, BAT *g, BAT *e, BAT *h)
1453 : __attribute__((__warn_unused_result__));
1454 : /*
1455 : * @- BAT Input/Output
1456 : * @multitable @columnfractions 0.08 0.7
1457 : * @item BAT *
1458 : * @tab BATload (str name)
1459 : * @item BAT *
1460 : * @tab BATsave (BAT *b)
1461 : * @item int
1462 : * @tab BATdelete (BAT *b)
1463 : * @end multitable
1464 : *
1465 : * A BAT created by COLnew is considered temporary until one calls the
1466 : * routine BATsave or BATmode. This routine reserves disk space and
1467 : * checks for name clashes in the BAT directory. It also makes the BAT
1468 : * persistent. The empty BAT is initially marked as ordered on both
1469 : * columns.
1470 : *
1471 : * Failure to read or write the BAT results in a NULL, otherwise it
1472 : * returns the BAT pointer.
1473 : *
1474 : * @- Heap Storage Modes
1475 : * The discriminative storage modes are memory-mapped, compressed, or
1476 : * loaded in memory. As can be seen in the bat record, each BAT has
1477 : * one BUN-heap (@emph{bn}), and possibly two heaps (@emph{hh} and
1478 : * @emph{th}) for variable-sized atoms.
1479 : */
1480 :
1481 : gdk_export gdk_return BATsave(BAT *b)
1482 : __attribute__((__warn_unused_result__));
1483 :
1484 : #define NOFARM (-1) /* indicate to GDKfilepath to create relative path */
1485 :
1486 : gdk_export char *GDKfilepath(int farmid, const char *dir, const char *nme, const char *ext);
1487 : gdk_export bool GDKinmemory(int farmid);
1488 : gdk_export bool GDKembedded(void);
1489 : gdk_export gdk_return GDKcreatedir(const char *nme);
1490 :
1491 : gdk_export void OIDXdestroy(BAT *b);
1492 :
1493 : /*
1494 : * @- Printing
1495 : * @multitable @columnfractions 0.08 0.7
1496 : * @item int
1497 : * @tab BATprintcolumns (stream *f, int argc, BAT *b[]);
1498 : * @end multitable
1499 : *
1500 : * The functions to convert BATs into ASCII. They are primarily meant for ease of
1501 : * debugging and to a lesser extent for output processing. Printing a
1502 : * BAT is done essentially by looping through its components, printing
1503 : * each association.
1504 : *
1505 : */
1506 : gdk_export gdk_return BATprintcolumns(stream *s, int argc, BAT *argv[]);
1507 : gdk_export gdk_return BATprint(stream *s, BAT *b);
1508 :
1509 : /*
1510 : * @- BAT clustering
1511 : * @multitable @columnfractions 0.08 0.7
1512 : * @item bool
1513 : * @tab BATordered (BAT *b)
1514 : * @end multitable
1515 : *
1516 : * When working in a main-memory situation, clustering of data on
1517 : * disk-pages is not important. Whenever mmap()-ed data is used
1518 : * intensively, reducing the number of page faults is a hot issue.
1519 : *
1520 : * The above functions rearrange data in MonetDB heaps (used for
1521 : * storing BUNs var-sized atoms, or accelerators). Applying these
1522 : * clusterings will allow that MonetDB's main-memory oriented
1523 : * algorithms work efficiently also in a disk-oriented context.
1524 : *
1525 : * BATordered starts a check on the tail values to see if they are
1526 : * ordered. The result is returned and stored in the tsorted field of
1527 : * the BAT.
1528 : */
1529 : gdk_export bool BATordered(BAT *b);
1530 : gdk_export bool BATordered_rev(BAT *b);
1531 : gdk_export gdk_return BATsort(BAT **sorted, BAT **order, BAT **groups, BAT *b, BAT *o, BAT *g, bool reverse, bool nilslast, bool stable)
1532 : __attribute__((__warn_unused_result__));
1533 :
1534 :
1535 : gdk_export void GDKqsort(void *restrict h, void *restrict t, const void *restrict base, size_t n, int hs, int ts, int tpe, bool reverse, bool nilslast);
1536 :
1537 : /* BAT is dense (i.e., BATtvoid() is true and tseqbase is not NIL) */
1538 : #define BATtdense(b) (!is_oid_nil((b)->tseqbase) && \
1539 : ((b)->tvheap == NULL || (b)->tvheap->free == 0))
1540 : #define BATtdensebi(bi) (!is_oid_nil((bi)->tseq) && \
1541 : ((bi)->vh == NULL || (bi)->vhfree == 0))
1542 : /* BATtvoid: BAT can be (or actually is) represented by TYPE_void */
1543 : #define BATtvoid(b) (BATtdense(b) || (b)->ttype==TYPE_void)
1544 : #define BATtkey(b) ((b)->tkey || BATtdense(b))
1545 :
1546 : /* set some properties that are trivial to deduce; called with theaplock
1547 : * held */
1548 : static inline void
1549 5348195 : BATsettrivprop(BAT *b)
1550 : {
1551 5348195 : assert(!is_oid_nil(b->hseqbase));
1552 5348195 : assert(is_oid_nil(b->tseqbase) || ATOMtype(b->ttype) == TYPE_oid);
1553 5348195 : if (b->ttype == TYPE_void) {
1554 1462254 : if (is_oid_nil(b->tseqbase)) {
1555 131 : b->tnonil = b->batCount == 0;
1556 131 : b->tnil = !b->tnonil;
1557 131 : b->trevsorted = true;
1558 131 : b->tkey = b->batCount <= 1;
1559 : } else {
1560 1462123 : b->tnonil = true;
1561 1462123 : b->tnil = false;
1562 1462123 : b->tkey = true;
1563 1462123 : b->trevsorted = b->batCount <= 1;
1564 : }
1565 1462254 : b->tsorted = true;
1566 3885941 : } else if (b->batCount <= 1) {
1567 1560441 : b->tnosorted = b->tnorevsorted = 0;
1568 1560441 : b->tnokey[0] = b->tnokey[1] = 0;
1569 1560441 : b->tunique_est = (double) b->batCount;
1570 1560441 : b->tkey = true;
1571 1560441 : if (ATOMlinear(b->ttype)) {
1572 1560441 : b->tsorted = true;
1573 1560441 : b->trevsorted = true;
1574 1560441 : if (b->batCount == 0) {
1575 1025641 : b->tminpos = BUN_NONE;
1576 1025641 : b->tmaxpos = BUN_NONE;
1577 1025641 : b->tnonil = true;
1578 1025641 : b->tnil = false;
1579 1025641 : if (b->ttype == TYPE_oid) {
1580 12326 : b->tseqbase = 0;
1581 : }
1582 534800 : } else if (b->ttype == TYPE_oid) {
1583 68416 : oid sqbs = ((const oid *) b->theap->base)[b->tbaseoff];
1584 68416 : if (is_oid_nil(sqbs)) {
1585 334 : b->tnonil = false;
1586 334 : b->tnil = true;
1587 334 : b->tminpos = BUN_NONE;
1588 334 : b->tmaxpos = BUN_NONE;
1589 : } else {
1590 68082 : b->tnonil = true;
1591 68082 : b->tnil = false;
1592 68082 : b->tminpos = 0;
1593 68082 : b->tmaxpos = 0;
1594 : }
1595 68416 : b->tseqbase = sqbs;
1596 466284 : } else if ((b->tvheap
1597 138457 : ? ATOMcmp(b->ttype,
1598 : b->tvheap->base + VarHeapVal(Tloc(b, 0), 0, b->twidth),
1599 : ATOMnilptr(b->ttype))
1600 327927 : : ATOMcmp(b->ttype, Tloc(b, 0),
1601 932668 : ATOMnilptr(b->ttype))) == 0) {
1602 : /* the only value is NIL */
1603 17676 : b->tminpos = BUN_NONE;
1604 17676 : b->tmaxpos = BUN_NONE;
1605 : } else {
1606 : /* the only value is both min and max */
1607 448608 : b->tminpos = 0;
1608 448608 : b->tmaxpos = 0;
1609 : }
1610 : } else {
1611 0 : b->tsorted = false;
1612 0 : b->trevsorted = false;
1613 0 : b->tminpos = BUN_NONE;
1614 0 : b->tmaxpos = BUN_NONE;
1615 : }
1616 2325500 : } else if (b->batCount == 2 && ATOMlinear(b->ttype)) {
1617 174550 : int c;
1618 174550 : if (b->tvheap)
1619 40117 : c = ATOMcmp(b->ttype,
1620 : b->tvheap->base + VarHeapVal(Tloc(b, 0), 0, b->twidth),
1621 : b->tvheap->base + VarHeapVal(Tloc(b, 0), 1, b->twidth));
1622 : else
1623 134433 : c = ATOMcmp(b->ttype, Tloc(b, 0), Tloc(b, 1));
1624 174527 : b->tsorted = c <= 0;
1625 174527 : b->tnosorted = !b->tsorted;
1626 174527 : b->trevsorted = c >= 0;
1627 174527 : b->tnorevsorted = !b->trevsorted;
1628 174527 : b->tkey = c != 0;
1629 174527 : b->tnokey[0] = 0;
1630 174527 : b->tnokey[1] = !b->tkey;
1631 174527 : b->tunique_est = (double) (1 + b->tkey);
1632 2150950 : } else if (!ATOMlinear(b->ttype)) {
1633 0 : b->tsorted = false;
1634 0 : b->trevsorted = false;
1635 0 : b->tminpos = BUN_NONE;
1636 0 : b->tmaxpos = BUN_NONE;
1637 : }
1638 5348072 : }
1639 :
1640 : static inline void
1641 310 : BATnegateprops(BAT *b)
1642 : {
1643 : /* disable all properties here */
1644 310 : b->tnonil = false;
1645 310 : b->tnil = false;
1646 310 : if (b->ttype) {
1647 310 : b->tsorted = false;
1648 310 : b->trevsorted = false;
1649 310 : b->tnosorted = 0;
1650 310 : b->tnorevsorted = 0;
1651 : }
1652 310 : b->tseqbase = oid_nil;
1653 310 : b->tkey = false;
1654 310 : b->tnokey[0] = 0;
1655 310 : b->tnokey[1] = 0;
1656 310 : b->tmaxpos = b->tminpos = BUN_NONE;
1657 310 : }
1658 :
1659 : /*
1660 : * @- GDK error handling
1661 : * @multitable @columnfractions 0.08 0.7
1662 : * @item str
1663 : * @tab
1664 : * GDKmessage
1665 : * @item bit
1666 : * @tab
1667 : * GDKfatal(str msg)
1668 : * @item int
1669 : * @tab
1670 : * GDKwarning(str msg)
1671 : * @item int
1672 : * @tab
1673 : * GDKerror (str msg)
1674 : * @item int
1675 : * @tab
1676 : * GDKgoterrors ()
1677 : * @item int
1678 : * @tab
1679 : * GDKsyserror (str msg)
1680 : * @item str
1681 : * @tab
1682 : * GDKerrbuf
1683 : * @item
1684 : * @tab GDKsetbuf (str buf)
1685 : * @end multitable
1686 : *
1687 : * The error handling mechanism is not sophisticated yet. Experience
1688 : * should show if this mechanism is sufficient. Most routines return
1689 : * a pointer with zero to indicate an error.
1690 : *
1691 : * The error messages are also copied to standard output. The last
1692 : * error message is kept around in a global variable.
1693 : *
1694 : * Error messages can also be collected in a user-provided buffer,
1695 : * instead of being echoed to a stream. This is a thread-specific
1696 : * issue; you want to decide on the error mechanism on a
1697 : * thread-specific basis. This effect is established with
1698 : * GDKsetbuf. The memory (de)allocation of this buffer, that must at
1699 : * least be 1024 chars long, is entirely by the user. A pointer to
1700 : * this buffer is kept in the pseudo-variable GDKerrbuf. Normally,
1701 : * this is a NULL pointer.
1702 : */
1703 : #define GDKMAXERRLEN 10240
1704 : #define GDKWARNING "!WARNING: "
1705 : #define GDKERROR "!ERROR: "
1706 : #define GDKMESSAGE "!OS: "
1707 : #define GDKFATAL "!FATAL: "
1708 :
1709 : /* Data Distilleries uses ICU for internationalization of some MonetDB error messages */
1710 :
1711 : #include "gdk_tracer.h"
1712 :
1713 : gdk_export gdk_return GDKtracer_fill_comp_info(BAT *id, BAT *component, BAT *log_level);
1714 :
1715 : #define GDKerror(format, ...) \
1716 : GDKtracer_log(__FILE__, __func__, __LINE__, M_ERROR, \
1717 : GDK, NULL, format, ##__VA_ARGS__)
1718 : #define GDKsyserr(errno, format, ...) \
1719 : GDKtracer_log(__FILE__, __func__, __LINE__, M_ERROR, \
1720 : GDK, GDKstrerror(errno, (char[64]){0}, 64), \
1721 : format, ##__VA_ARGS__)
1722 : #define GDKsyserror(format, ...) GDKsyserr(errno, format, ##__VA_ARGS__)
1723 :
1724 : gdk_export void GDKclrerr(void);
1725 :
1726 :
1727 : /* tfastins* family: update a value at a particular location in the bat
1728 : * bunfastapp* family: append a value to the bat
1729 : * *_nocheck: do not check whether the capacity is large enough
1730 : * * (without _nocheck): check bat capacity and possibly extend
1731 : *
1732 : * This means, for tfastins* it is the caller's responsibility to set
1733 : * the batCount and theap->free values correctly (e.g. by calling
1734 : * BATsetcount(), and for *_nocheck to make sure there is enough space
1735 : * allocated in the theap (tvheap for variable-sized types is still
1736 : * extended if needed, making that these functions can fail).
1737 : */
1738 : static inline gdk_return __attribute__((__warn_unused_result__))
1739 103267585 : tfastins_nocheckVAR(BAT *b, BUN p, const void *v)
1740 : {
1741 103267585 : var_t d;
1742 103267585 : gdk_return rc;
1743 103267585 : assert(b->tbaseoff == 0);
1744 103267585 : assert(b->theap->parentid == b->batCacheid);
1745 103267585 : MT_lock_set(&b->theaplock);
1746 103565072 : rc = ATOMputVAR(b, &d, v);
1747 103607306 : MT_lock_unset(&b->theaplock);
1748 104633947 : if (rc != GDK_SUCCEED)
1749 : return rc;
1750 104482326 : if (b->twidth < SIZEOF_VAR_T &&
1751 92811233 : (b->twidth <= 2 ? d - GDK_VAROFFSET : d) >= ((size_t) 1 << (8 << b->tshift))) {
1752 : /* doesn't fit in current heap, upgrade it */
1753 13692 : rc = GDKupgradevarheap(b, d, 0, MAX(p, b->batCount));
1754 13692 : if (rc != GDK_SUCCEED)
1755 : return rc;
1756 : }
1757 104482326 : switch (b->twidth) {
1758 29880429 : case 1:
1759 29880429 : ((uint8_t *) b->theap->base)[p] = (uint8_t) (d - GDK_VAROFFSET);
1760 29880429 : break;
1761 17409720 : case 2:
1762 17409720 : ((uint16_t *) b->theap->base)[p] = (uint16_t) (d - GDK_VAROFFSET);
1763 17409720 : break;
1764 45588930 : case 4:
1765 45588930 : ((uint32_t *) b->theap->base)[p] = (uint32_t) d;
1766 45588930 : break;
1767 : #if SIZEOF_VAR_T == 8
1768 11603247 : case 8:
1769 11603247 : ((uint64_t *) b->theap->base)[p] = (uint64_t) d;
1770 11603247 : break;
1771 : #endif
1772 : default:
1773 0 : MT_UNREACHABLE();
1774 : }
1775 : return GDK_SUCCEED;
1776 : }
1777 :
1778 : static inline gdk_return __attribute__((__warn_unused_result__))
1779 364048555 : tfastins_nocheckFIX(BAT *b, BUN p, const void *v)
1780 : {
1781 364048555 : return ATOMputFIX(b->ttype, Tloc(b, p), v);
1782 : }
1783 :
1784 : static inline gdk_return __attribute__((__warn_unused_result__))
1785 370869667 : tfastins_nocheck(BAT *b, BUN p, const void *v)
1786 : {
1787 370869667 : assert(b->theap->parentid == b->batCacheid);
1788 370869667 : assert(b->tbaseoff == 0);
1789 370869667 : if (b->ttype == TYPE_void) {
1790 : ;
1791 370869667 : } else if (ATOMstorage(b->ttype) == TYPE_msk) {
1792 0 : mskSetVal(b, p, * (msk *) v);
1793 370869667 : } else if (b->tvheap) {
1794 40021491 : return tfastins_nocheckVAR(b, p, v);
1795 : } else {
1796 330848176 : return tfastins_nocheckFIX(b, p, v);
1797 : }
1798 : return GDK_SUCCEED;
1799 : }
1800 :
1801 : static inline gdk_return __attribute__((__warn_unused_result__))
1802 347653901 : tfastins(BAT *b, BUN p, const void *v)
1803 : {
1804 347653901 : if (p >= BATcapacity(b)) {
1805 0 : if (p >= BUN_MAX) {
1806 0 : GDKerror("tfastins: too many elements to accommodate (" BUNFMT ")\n", BUN_MAX);
1807 0 : return GDK_FAIL;
1808 : }
1809 0 : BUN sz = BATgrows(b);
1810 0 : if (sz <= p)
1811 0 : sz = p + BATTINY;
1812 0 : gdk_return rc = BATextend(b, sz);
1813 0 : if (rc != GDK_SUCCEED)
1814 : return rc;
1815 : }
1816 347653901 : return tfastins_nocheck(b, p, v);
1817 : }
1818 :
1819 : static inline gdk_return __attribute__((__warn_unused_result__))
1820 8438092 : bunfastapp_nocheck(BAT *b, const void *v)
1821 : {
1822 8438092 : BUN p = b->batCount;
1823 8438092 : if (ATOMstorage(b->ttype) == TYPE_msk && p % 32 == 0)
1824 0 : ((uint32_t *) b->theap->base)[p / 32] = 0;
1825 8438092 : gdk_return rc = tfastins_nocheck(b, p, v);
1826 8439007 : if (rc == GDK_SUCCEED) {
1827 8439546 : b->batCount++;
1828 8439546 : if (ATOMstorage(b->ttype) == TYPE_msk) {
1829 0 : if (p % 32 == 0)
1830 0 : b->theap->free += 4;
1831 : } else
1832 8439546 : b->theap->free += b->twidth;
1833 : }
1834 8439007 : return rc;
1835 : }
1836 :
1837 : static inline gdk_return __attribute__((__warn_unused_result__))
1838 347651334 : bunfastapp(BAT *b, const void *v)
1839 : {
1840 347651334 : BUN p = b->batCount;
1841 347651334 : if (ATOMstorage(b->ttype) == TYPE_msk && p % 32 == 0)
1842 0 : ((uint32_t *) b->theap->base)[p / 32] = 0;
1843 347651334 : gdk_return rc = tfastins(b, p, v);
1844 343065920 : if (rc == GDK_SUCCEED) {
1845 338068068 : b->batCount++;
1846 338068068 : if (ATOMstorage(b->ttype) == TYPE_msk) {
1847 0 : if (p % 32 == 0)
1848 0 : b->theap->free += 4;
1849 : } else
1850 338068068 : b->theap->free += b->twidth;
1851 : }
1852 343065920 : return rc;
1853 : }
1854 :
1855 : #define bunfastappTYPE(TYPE, b, v) \
1856 : (BATcount(b) >= BATcapacity(b) && \
1857 : ((BATcount(b) == BUN_MAX && \
1858 : (GDKerror("bunfastapp: too many elements to accommodate (" BUNFMT ")\n", BUN_MAX), \
1859 : true)) || \
1860 : BATextend((b), BATgrows(b)) != GDK_SUCCEED) ? \
1861 : GDK_FAIL : \
1862 : (assert((b)->theap->parentid == (b)->batCacheid), \
1863 : (b)->theap->free += sizeof(TYPE), \
1864 : ((TYPE *) (b)->theap->base)[(b)->batCount++] = * (const TYPE *) (v), \
1865 : GDK_SUCCEED))
1866 :
1867 : static inline gdk_return __attribute__((__warn_unused_result__))
1868 344 : bunfastapp_nocheckVAR(BAT *b, const void *v)
1869 : {
1870 344 : gdk_return rc;
1871 344 : rc = tfastins_nocheckVAR(b, b->batCount, v);
1872 344 : if (rc == GDK_SUCCEED) {
1873 344 : b->batCount++;
1874 344 : b->theap->free += b->twidth;
1875 : }
1876 344 : return rc;
1877 : }
1878 :
1879 : /*
1880 : * @- Column Imprints Functions
1881 : *
1882 : * @multitable @columnfractions 0.08 0.7
1883 : * @item BAT*
1884 : * @tab
1885 : * BATimprints (BAT *b)
1886 : * @end multitable
1887 : *
1888 : * The column imprints index structure.
1889 : *
1890 : */
1891 :
1892 : gdk_export gdk_return BATimprints(BAT *b);
1893 : gdk_export void IMPSdestroy(BAT *b);
1894 : gdk_export lng IMPSimprintsize(BAT *b);
1895 :
1896 : /* Strimps exported functions */
1897 : gdk_export gdk_return STRMPcreate(BAT *b, BAT *s);
1898 : gdk_export BAT *STRMPfilter(BAT *b, BAT *s, const char *q, const bool keep_nils);
1899 : gdk_export void STRMPdestroy(BAT *b);
1900 : gdk_export bool BAThasstrimps(BAT *b);
1901 : gdk_export gdk_return BATsetstrimps(BAT *b);
1902 :
1903 : /* Rtree structure functions */
1904 : #ifdef HAVE_RTREE
1905 : gdk_export bool RTREEexists(BAT *b);
1906 : gdk_export bool RTREEexists_bid(bat bid);
1907 : gdk_export gdk_return BATrtree(BAT *wkb, BAT* mbr);
1908 : /* inMBR is really a struct mbr * from geom module, but that is not
1909 : * available here */
1910 : gdk_export BUN* RTREEsearch(BAT *b, const void *inMBR, int result_limit);
1911 : #endif
1912 :
1913 : gdk_export void RTREEdestroy(BAT *b);
1914 : gdk_export void RTREEfree(BAT *b);
1915 :
1916 : /* The ordered index structure */
1917 :
1918 : gdk_export gdk_return BATorderidx(BAT *b, bool stable);
1919 : gdk_export gdk_return GDKmergeidx(BAT *b, BAT**a, int n_ar);
1920 : gdk_export bool BATcheckorderidx(BAT *b);
1921 :
1922 : #include "gdk_delta.h"
1923 : #include "gdk_hash.h"
1924 : #include "gdk_bbp.h"
1925 : #include "gdk_utils.h"
1926 :
1927 : /* functions defined in gdk_bat.c */
1928 : gdk_export gdk_return void_inplace(BAT *b, oid id, const void *val, bool force)
1929 : __attribute__((__warn_unused_result__));
1930 : gdk_export BAT *BATattach(int tt, const char *heapfile, role_t role);
1931 :
1932 : #ifdef NATIVE_WIN32
1933 : #ifdef _MSC_VER
1934 : #define fileno _fileno
1935 : #endif
1936 : #define fdopen _fdopen
1937 : #define putenv _putenv
1938 : #endif
1939 :
1940 : /* Return a pointer to the value contained in V. Also see VALget
1941 : * which returns a void *. */
1942 : static inline const void *
1943 301018503 : VALptr(const ValRecord *v)
1944 : {
1945 301018503 : switch (ATOMstorage(v->vtype)) {
1946 613961 : case TYPE_void: return (const void *) &v->val.oval;
1947 0 : case TYPE_msk: return (const void *) &v->val.mval;
1948 13726428 : case TYPE_bte: return (const void *) &v->val.btval;
1949 1212867 : case TYPE_sht: return (const void *) &v->val.shval;
1950 124634698 : case TYPE_int: return (const void *) &v->val.ival;
1951 13125 : case TYPE_flt: return (const void *) &v->val.fval;
1952 566319 : case TYPE_dbl: return (const void *) &v->val.dval;
1953 67323074 : case TYPE_lng: return (const void *) &v->val.lval;
1954 : #ifdef HAVE_HGE
1955 16740 : case TYPE_hge: return (const void *) &v->val.hval;
1956 : #endif
1957 771 : case TYPE_uuid: return (const void *) &v->val.uval;
1958 268286 : case TYPE_ptr: return (const void *) &v->val.pval;
1959 92639557 : case TYPE_str: return (const void *) v->val.sval;
1960 2677 : default: return (const void *) v->val.pval;
1961 : }
1962 : }
1963 :
1964 : #define THREADS 1024 /* maximum value for gdk_nr_threads */
1965 :
1966 : gdk_export stream *GDKstdout;
1967 : gdk_export stream *GDKstdin;
1968 :
1969 : #define GDKerrbuf (GDKgetbuf())
1970 :
1971 : static inline bat
1972 385900597 : BBPcheck(bat x)
1973 : {
1974 385900597 : if (!is_bat_nil(x)) {
1975 385499552 : assert(x > 0);
1976 :
1977 385499552 : if (x < 0 || x >= getBBPsize() || BBP_logical(x) == NULL) {
1978 0 : TRC_DEBUG(CHECK_, "range error %d\n", (int) x);
1979 : } else {
1980 385005466 : assert(BBP_pid(x) == 0 || BBP_pid(x) == MT_getpid());
1981 384995472 : return x;
1982 : }
1983 : }
1984 : return 0;
1985 : }
1986 :
1987 : gdk_export BAT *BATdescriptor(bat i);
1988 :
1989 : static inline void *
1990 17995114 : Tpos(BATiter *bi, BUN p)
1991 : {
1992 17995114 : assert(bi->base == NULL);
1993 17995114 : if (bi->vh) {
1994 11468148 : oid o;
1995 11468148 : assert(!is_oid_nil(bi->tseq));
1996 11468148 : if (((ccand_t *) bi->vh)->type == CAND_NEGOID) {
1997 11468148 : BUN nexc = (bi->vhfree - sizeof(ccand_t)) / SIZEOF_OID;
1998 11468148 : o = bi->tseq + p;
1999 11468148 : if (nexc > 0) {
2000 11468155 : const oid *exc = (const oid *) (bi->vh->base + sizeof(ccand_t));
2001 11468155 : if (o >= exc[0]) {
2002 23877 : if (o + nexc > exc[nexc - 1]) {
2003 : o += nexc;
2004 : } else {
2005 5687 : BUN lo = 0;
2006 5687 : BUN hi = nexc - 1;
2007 32008 : while (hi - lo > 1) {
2008 20634 : BUN mid = (hi + lo) / 2;
2009 20634 : if (exc[mid] - mid > o)
2010 : hi = mid;
2011 : else
2012 13287 : lo = mid;
2013 : }
2014 5687 : o += hi;
2015 : }
2016 : }
2017 : }
2018 : } else {
2019 0 : const uint32_t *msk = (const uint32_t *) (bi->vh->base + sizeof(ccand_t));
2020 0 : BUN nmsk = (bi->vhfree - sizeof(ccand_t)) / sizeof(uint32_t);
2021 0 : o = 0;
2022 0 : for (BUN i = 0; i < nmsk; i++) {
2023 0 : uint32_t m = candmask_pop(msk[i]);
2024 0 : if (o + m > p) {
2025 0 : m = msk[i];
2026 0 : for (i = 0; i < 32; i++) {
2027 0 : if (m & (1U << i) && ++o == p)
2028 : break;
2029 : }
2030 : break;
2031 : }
2032 0 : o += m;
2033 : }
2034 : }
2035 11468148 : bi->tvid = o;
2036 6526966 : } else if (is_oid_nil(bi->tseq)) {
2037 0 : bi->tvid = oid_nil;
2038 : } else {
2039 6526966 : bi->tvid = bi->tseq + p;
2040 : }
2041 17995114 : return (void *) &bi->tvid;
2042 : }
2043 :
2044 : static inline bool
2045 401 : Tmskval(BATiter *bi, BUN p)
2046 : {
2047 401 : assert(ATOMstorage(bi->type) == TYPE_msk);
2048 401 : return ((uint32_t *) bi->base)[p / 32] & (1U << (p % 32));
2049 : }
2050 :
2051 : static inline void *
2052 401 : Tmsk(BATiter *bi, BUN p)
2053 : {
2054 401 : bi->tmsk = Tmskval(bi, p);
2055 401 : return &bi->tmsk;
2056 : }
2057 :
2058 : /* return the oid value at BUN position p from the (v)oid bat b
2059 : * works with any TYPE_void or TYPE_oid bat */
2060 : static inline oid
2061 23380221 : BUNtoid(BAT *b, BUN p)
2062 : {
2063 23380221 : assert(ATOMtype(b->ttype) == TYPE_oid);
2064 : /* BATcount is the number of valid entries, so with
2065 : * exceptions, the last value can well be larger than
2066 : * b->tseqbase + BATcount(b) */
2067 23380221 : assert(p < BATcount(b));
2068 23380221 : assert(b->ttype == TYPE_void || b->tvheap == NULL);
2069 23380221 : if (is_oid_nil(b->tseqbase)) {
2070 22849622 : if (b->ttype == TYPE_void)
2071 0 : return oid_nil;
2072 22849622 : MT_lock_set(&b->theaplock);
2073 22713083 : oid o = ((const oid *) b->theap->base)[p + b->tbaseoff];
2074 22713083 : MT_lock_unset(&b->theaplock);
2075 22580081 : return o;
2076 : }
2077 530599 : if (b->ttype == TYPE_oid || b->tvheap == NULL) {
2078 517367 : return b->tseqbase + p;
2079 : }
2080 : /* b->tvheap != NULL, so we know there will be no parallel
2081 : * modifications (so no locking) */
2082 13232 : BATiter bi = bat_iterator_nolock(b);
2083 13232 : return * (oid *) Tpos(&bi, p);
2084 : }
2085 :
2086 : /*
2087 : * @+ Transaction Management
2088 : */
2089 : gdk_export gdk_return TMsubcommit_list(bat *restrict subcommit, BUN *restrict sizes, int cnt, lng logno)
2090 : __attribute__((__warn_unused_result__));
2091 :
2092 : /*
2093 : * @- Delta Management
2094 : * @multitable @columnfractions 0.08 0.6
2095 : * @item BAT *
2096 : * @tab BATcommit (BAT *b)
2097 : * @end multitable
2098 : *
2099 : * The BAT keeps track of updates with respect to a 'previous state'.
2100 : * Do not confuse 'previous state' with 'stable' or 'commited-on-disk',
2101 : * because these concepts are not always the same. In particular, they
2102 : * diverge when BATcommit and BATfakecommit are called explicitly,
2103 : * bypassing the normal global TMcommit protocol (some applications need
2104 : * that flexibility).
2105 : *
2106 : * BATcommit make the current BAT state the new 'stable state'. This
2107 : * happens inside the global TMcommit on all persistent BATs previous
2108 : * to writing all bats to persistent storage using a BBPsync.
2109 : */
2110 : gdk_export void BATcommit(BAT *b, BUN size);
2111 :
2112 : /*
2113 : * @+ BAT Alignment and BAT views
2114 : * @multitable @columnfractions 0.08 0.7
2115 : * @item int
2116 : * @tab ALIGNsynced (BAT* b1, BAT* b2)
2117 : * @item int
2118 : * @tab ALIGNsync (BAT *b1, BAT *b2)
2119 : * @item int
2120 : * @tab ALIGNrelated (BAT *b1, BAT *b2)
2121 : *
2122 : * @item BAT*
2123 : * @tab VIEWcreate (oid seq, BAT *b, BUN lo, BUN hi)
2124 : * @item int
2125 : * @tab isVIEW (BAT *b)
2126 : * @item bat
2127 : * @tab VIEWhparent (BAT *b)
2128 : * @item bat
2129 : * @tab VIEWtparent (BAT *b)
2130 : * @end multitable
2131 : *
2132 : * Alignments of two columns of a BAT means that the system knows
2133 : * whether these two columns are exactly equal. Relatedness of two
2134 : * BATs means that one pair of columns (either head or tail) of both
2135 : * BATs is aligned. The first property is checked by ALIGNsynced, the
2136 : * latter by ALIGNrelated.
2137 : *
2138 : * All algebraic BAT commands propagate the properties - including
2139 : * alignment properly on their results.
2140 : *
2141 : * VIEW BATs are BATs that lend their storage from a parent BAT. They
2142 : * are just a descriptor that points to the data in this parent BAT. A
2143 : * view is created with VIEWcreate. The cache id of the parent (if
2144 : * any) is returned by VIEWtparent (otherwise it returns 0).
2145 : *
2146 : * VIEW bats are read-only!!
2147 : */
2148 : gdk_export int ALIGNsynced(BAT *b1, BAT *b2);
2149 :
2150 : gdk_export void BATassertProps(BAT *b);
2151 :
2152 : gdk_export BAT *VIEWcreate(oid seq, BAT *b, BUN l, BUN h);
2153 : gdk_export void VIEWbounds(BAT *b, BAT *view, BUN l, BUN h);
2154 :
2155 : #define ALIGNapp(x, f, e) \
2156 : do { \
2157 : if (!(f)) { \
2158 : MT_lock_set(&(x)->theaplock); \
2159 : if ((x)->batRestricted == BAT_READ || \
2160 : ((ATOMIC_GET(&(x)->theap->refs) & HEAPREFS) > 1)) { \
2161 : GDKerror("access denied to %s, aborting.\n", BATgetId(x)); \
2162 : MT_lock_unset(&(x)->theaplock); \
2163 : return (e); \
2164 : } \
2165 : MT_lock_unset(&(x)->theaplock); \
2166 : } \
2167 : } while (false)
2168 :
2169 : /*
2170 : * @+ BAT Iterators
2171 : * @multitable @columnfractions 0.15 0.7
2172 : * @item BATloop
2173 : * @tab
2174 : * (BAT *b; BUN p, BUN q)
2175 : * @item BATloopDEL
2176 : * @tab
2177 : * (BAT *b; BUN p; BUN q; int dummy)
2178 : * @item HASHloop
2179 : * @tab
2180 : * (BAT *b; Hash *h, size_t dummy; ptr value)
2181 : * @item HASHloop_bte
2182 : * @tab
2183 : * (BAT *b; Hash *h, size_t idx; bte *value, BUN w)
2184 : * @item HASHloop_sht
2185 : * @tab
2186 : * (BAT *b; Hash *h, size_t idx; sht *value, BUN w)
2187 : * @item HASHloop_int
2188 : * @tab
2189 : * (BAT *b; Hash *h, size_t idx; int *value, BUN w)
2190 : * @item HASHloop_flt
2191 : * @tab
2192 : * (BAT *b; Hash *h, size_t idx; flt *value, BUN w)
2193 : * @item HASHloop_lng
2194 : * @tab
2195 : * (BAT *b; Hash *h, size_t idx; lng *value, BUN w)
2196 : * @item HASHloop_hge
2197 : * @tab
2198 : * (BAT *b; Hash *h, size_t idx; hge *value, BUN w)
2199 : * @item HASHloop_dbl
2200 : * @tab
2201 : * (BAT *b; Hash *h, size_t idx; dbl *value, BUN w)
2202 : * @item HASHloop_str
2203 : * @tab
2204 : * (BAT *b; Hash *h, size_t idx; str value, BUN w)
2205 : * @item HASHlooploc
2206 : * @tab
2207 : * (BAT *b; Hash *h, size_t idx; ptr value, BUN w)
2208 : * @item HASHloopvar
2209 : * @tab
2210 : * (BAT *b; Hash *h, size_t idx; ptr value, BUN w)
2211 : * @end multitable
2212 : *
2213 : * The @emph{BATloop()} looks like a function call, but is actually a
2214 : * macro.
2215 : *
2216 : * @- simple sequential scan
2217 : * The first parameter is a BAT, the p and q are BUN pointers, where p
2218 : * is the iteration variable.
2219 : */
2220 : #define BATloop(r, p, q) \
2221 : for (q = BATcount(r), p = 0; p < q; p++)
2222 :
2223 : /*
2224 : * @+ Common BAT Operations
2225 : * Much used, but not necessarily kernel-operations on BATs.
2226 : *
2227 : * For each BAT we maintain its dimensions as separately accessible
2228 : * properties. They can be used to improve query processing at higher
2229 : * levels.
2230 : */
2231 : enum prop_t {
2232 : GDK_MIN_BOUND, /* MINimum allowed value for range partitions [min, max> */
2233 : GDK_MAX_BOUND, /* MAXimum of the range partitions [min, max>, ie. excluding this max value */
2234 : GDK_NOT_NULL, /* bat bound to be not null */
2235 : /* CURRENTLY_NO_PROPERTIES_DEFINED, */
2236 : };
2237 :
2238 : gdk_export ValPtr BATgetprop(BAT *b, enum prop_t idx);
2239 : gdk_export ValPtr BATgetprop_nolock(BAT *b, enum prop_t idx);
2240 : gdk_export void BATrmprop(BAT *b, enum prop_t idx);
2241 : gdk_export void BATrmprop_nolock(BAT *b, enum prop_t idx);
2242 : gdk_export ValPtr BATsetprop(BAT *b, enum prop_t idx, int type, const void *v);
2243 : gdk_export ValPtr BATsetprop_nolock(BAT *b, enum prop_t idx, int type, const void *v);
2244 :
2245 : /*
2246 : * @- BAT relational operators
2247 : *
2248 : * The full-materialization policy intermediate results in MonetDB
2249 : * means that a join can produce an arbitrarily large result and choke
2250 : * the system. The Data Distilleries tool therefore first computes the
2251 : * join result size before the actual join (better waste time than
2252 : * crash the server). To exploit that perfect result size knowledge,
2253 : * an result-size estimate parameter was added to all equi-join
2254 : * implementations. TODO: add this for
2255 : * semijoin/select/unique/diff/intersect
2256 : *
2257 : * @- modes for thethajoin
2258 : */
2259 : #define JOIN_EQ 0
2260 : #define JOIN_LT (-1)
2261 : #define JOIN_LE (-2)
2262 : #define JOIN_GT 1
2263 : #define JOIN_GE 2
2264 : #define JOIN_BAND 3
2265 : #define JOIN_NE (-3)
2266 :
2267 : gdk_export BAT *BATselect(BAT *b, BAT *s, const void *tl, const void *th, bool li, bool hi, bool anti);
2268 : gdk_export BAT *BATthetaselect(BAT *b, BAT *s, const void *val, const char *op);
2269 :
2270 : gdk_export BAT *BATconstant(oid hseq, int tt, const void *val, BUN cnt, role_t role);
2271 : gdk_export gdk_return BATsubcross(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool max_one)
2272 : __attribute__((__warn_unused_result__));
2273 : gdk_export gdk_return BAToutercross(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool max_one)
2274 : __attribute__((__warn_unused_result__));
2275 :
2276 : gdk_export gdk_return BATleftjoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, BUN estimate)
2277 : __attribute__((__warn_unused_result__));
2278 : gdk_export gdk_return BATmarkjoin(BAT **r1p, BAT **r2p, BAT **r3p, BAT *l, BAT *r, BAT *sl, BAT *sr, BUN estimate)
2279 : __attribute__((__warn_unused_result__));
2280 : gdk_export gdk_return BATouterjoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, bool match_one, BUN estimate)
2281 : __attribute__((__warn_unused_result__));
2282 : gdk_export gdk_return BATthetajoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, int op, bool nil_matches, BUN estimate)
2283 : __attribute__((__warn_unused_result__));
2284 : gdk_export gdk_return BATsemijoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, bool max_one, BUN estimate)
2285 : __attribute__((__warn_unused_result__));
2286 : gdk_export BAT *BATintersect(BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, bool max_one, BUN estimate);
2287 : gdk_export BAT *BATdiff(BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, bool not_in, BUN estimate);
2288 : gdk_export gdk_return BATjoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, BUN estimate)
2289 : __attribute__((__warn_unused_result__));
2290 : gdk_export BUN BATguess_uniques(BAT *b, struct canditer *ci);
2291 : gdk_export gdk_return BATbandjoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, const void *c1, const void *c2, bool li, bool hi, BUN estimate)
2292 : __attribute__((__warn_unused_result__));
2293 : gdk_export gdk_return BATrangejoin(BAT **r1p, BAT **r2p, BAT *l, BAT *rl, BAT *rh, BAT *sl, BAT *sr, bool li, bool hi, bool anti, bool symmetric, BUN estimate)
2294 : __attribute__((__warn_unused_result__));
2295 : gdk_export BAT *BATproject(BAT *restrict l, BAT *restrict r);
2296 : gdk_export BAT *BATproject2(BAT *restrict l, BAT *restrict r1, BAT *restrict r2);
2297 : gdk_export BAT *BATprojectchain(BAT **bats);
2298 :
2299 : gdk_export BAT *BATslice(BAT *b, BUN low, BUN high);
2300 :
2301 : gdk_export BAT *BATunique(BAT *b, BAT *s);
2302 :
2303 : gdk_export gdk_return BATfirstn(BAT **topn, BAT **gids, BAT *b, BAT *cands, BAT *grps, BUN n, bool asc, bool nilslast, bool distinct)
2304 : __attribute__((__warn_unused_result__));
2305 :
2306 : #include "gdk_calc.h"
2307 :
2308 : gdk_export gdk_return GDKtoupper(char **restrict buf, size_t *restrict buflen, const char *restrict s);
2309 : gdk_export gdk_return GDKtolower(char **restrict buf, size_t *restrict buflen, const char *restrict s);
2310 : gdk_export gdk_return GDKcasefold(char **restrict buf, size_t *restrict buflen, const char *restrict s);
2311 : gdk_export int GDKstrncasecmp(const char *str1, const char *str2, size_t l1, size_t l2);
2312 : gdk_export int GDKstrcasecmp(const char *s1, const char *s2);
2313 : gdk_export char *GDKstrcasestr(const char *haystack, const char *needle);
2314 : gdk_export BAT *BATtoupper(BAT *b, BAT *s);
2315 : gdk_export BAT *BATtolower(BAT *b, BAT *s);
2316 : gdk_export BAT *BATcasefold(BAT *b, BAT *s);
2317 : gdk_export gdk_return GDKasciify(char **restrict buf, size_t *restrict buflen, const char *restrict s);
2318 : gdk_export BAT *BATasciify(BAT *b, BAT *s);
2319 :
2320 : /*
2321 : * @- BAT sample operators
2322 : *
2323 : * @multitable @columnfractions 0.08 0.7
2324 : * @item BAT *
2325 : * @tab BATsample (BAT *b, n)
2326 : * @end multitable
2327 : *
2328 : * The routine BATsample returns a random sample on n BUNs of a BAT.
2329 : *
2330 : */
2331 : gdk_export BAT *BATsample(BAT *b, BUN n);
2332 : gdk_export BAT *BATsample_with_seed(BAT *b, BUN n, uint64_t seed);
2333 :
2334 : /*
2335 : *
2336 : */
2337 : #define MAXPARAMS 32
2338 :
2339 : #define CHECK_QRY_TIMEOUT_SHIFT 14
2340 : #define CHECK_QRY_TIMEOUT_STEP (1 << CHECK_QRY_TIMEOUT_SHIFT)
2341 : #define CHECK_QRY_TIMEOUT_MASK (CHECK_QRY_TIMEOUT_STEP - 1)
2342 :
2343 : #define TIMEOUT_MSG "Timeout was reached!"
2344 : #define INTERRUPT_MSG "Query interrupted!"
2345 : #define DISCONNECT_MSG "Client is disconnected!"
2346 : #define EXITING_MSG "Server is exiting!"
2347 :
2348 : #define QRY_TIMEOUT (-1) /* query timed out */
2349 : #define QRY_INTERRUPT (-2) /* client indicated interrupt */
2350 : #define QRY_DISCONNECT (-3) /* client disconnected */
2351 :
2352 : static const char *
2353 3 : TIMEOUT_MESSAGE(QryCtx *qc)
2354 : {
2355 3 : if (GDKexiting())
2356 : return EXITING_MSG;
2357 3 : if (qc) {
2358 3 : switch (qc->endtime) {
2359 : case QRY_TIMEOUT:
2360 : return TIMEOUT_MSG;
2361 0 : case QRY_INTERRUPT:
2362 0 : return INTERRUPT_MSG;
2363 0 : case QRY_DISCONNECT:
2364 0 : return DISCONNECT_MSG;
2365 : default:
2366 0 : MT_UNREACHABLE();
2367 : }
2368 : }
2369 : return NULL;
2370 : }
2371 :
2372 : static inline void
2373 3 : TIMEOUT_ERROR(QryCtx *qc, const char *file, const char *func, int lineno)
2374 : {
2375 3 : const char *e = TIMEOUT_MESSAGE(qc);
2376 3 : if (e) {
2377 3 : GDKtracer_log(file, func, lineno, M_ERROR, GDK, NULL,
2378 : "%s\n", e);
2379 : }
2380 3 : }
2381 :
2382 : #define TIMEOUT_HANDLER(rtpe, qc) \
2383 : do { \
2384 : TIMEOUT_ERROR(qc, __FILE__, __func__, __LINE__); \
2385 : return rtpe; \
2386 : } while(0)
2387 :
2388 : static inline bool
2389 10311994 : TIMEOUT_TEST(QryCtx *qc)
2390 : {
2391 10311994 : if (qc == NULL)
2392 : return false;
2393 10312372 : if (qc->endtime < 0)
2394 : return true;
2395 10312370 : if (qc->endtime && GDKusec() > qc->endtime) {
2396 3 : qc->endtime = QRY_TIMEOUT;
2397 3 : return true;
2398 : }
2399 10312367 : switch (bstream_getoob(qc->bs)) {
2400 0 : case -1:
2401 0 : qc->endtime = QRY_DISCONNECT;
2402 0 : return true;
2403 : case 0:
2404 : return false;
2405 0 : default:
2406 0 : qc->endtime = QRY_INTERRUPT;
2407 0 : return true;
2408 : }
2409 : }
2410 :
2411 : #define GOTO_LABEL_TIMEOUT_HANDLER(label, qc) \
2412 : do { \
2413 : TIMEOUT_ERROR(qc, __FILE__, __func__, __LINE__); \
2414 : goto label; \
2415 : } while(0)
2416 :
2417 : #define GDK_CHECK_TIMEOUT_BODY(qc, callback) \
2418 : do { \
2419 : if (GDKexiting() || TIMEOUT_TEST(qc)) { \
2420 : callback; \
2421 : } \
2422 : } while (0)
2423 :
2424 : #define GDK_CHECK_TIMEOUT(qc, counter, callback) \
2425 : do { \
2426 : if (counter > CHECK_QRY_TIMEOUT_STEP) { \
2427 : GDK_CHECK_TIMEOUT_BODY(qc, callback); \
2428 : counter = 0; \
2429 : } else { \
2430 : counter++; \
2431 : } \
2432 : } while (0)
2433 :
2434 : /* here are some useful constructs to iterate a number of times (the
2435 : * REPEATS argument--only evaluated once) and checking for a timeout
2436 : * every once in a while; the QC->endtime value is a variable of type lng
2437 : * which is either 0 or the GDKusec() compatible time after which the
2438 : * loop should terminate; check for this condition after the loop using
2439 : * the TIMEOUT_CHECK macro; in order to break out of any of these loops,
2440 : * use TIMEOUT_LOOP_BREAK since plain break won't do it; it is perfectly
2441 : * ok to use continue inside the body */
2442 :
2443 : /* use IDX as a loop variable (already declared), initializing it to 0
2444 : * and incrementing it on each iteration */
2445 : #define TIMEOUT_LOOP_IDX(IDX, REPEATS, QC) \
2446 : for (BUN REPS = (IDX = 0, (REPEATS)); REPS > 0; REPS = 0) /* "loops" at most once */ \
2447 : for (BUN CTR1 = 0, END1 = (REPS + CHECK_QRY_TIMEOUT_STEP) >> CHECK_QRY_TIMEOUT_SHIFT; CTR1 < END1 && !GDKexiting() && ((QC) == NULL || (QC)->endtime >= 0); CTR1++) \
2448 : if (CTR1 > 0 && TIMEOUT_TEST(QC)) { \
2449 : break; \
2450 : } else \
2451 : for (BUN CTR2 = 0, END2 = CTR1 == END1 - 1 ? REPS & CHECK_QRY_TIMEOUT_MASK : CHECK_QRY_TIMEOUT_STEP; CTR2 < END2; CTR2++, IDX++)
2452 :
2453 : /* declare and use IDX as a loop variable, initializing it to 0 and
2454 : * incrementing it on each iteration */
2455 : #define TIMEOUT_LOOP_IDX_DECL(IDX, REPEATS, QC) \
2456 : for (BUN IDX = 0, REPS = (REPEATS); REPS > 0; REPS = 0) /* "loops" at most once */ \
2457 : for (BUN CTR1 = 0, END1 = (REPS + CHECK_QRY_TIMEOUT_STEP) >> CHECK_QRY_TIMEOUT_SHIFT; CTR1 < END1 && !GDKexiting() && ((QC) == NULL || (QC)->endtime >= 0); CTR1++) \
2458 : if (CTR1 > 0 && TIMEOUT_TEST(QC)) { \
2459 : break; \
2460 : } else \
2461 : for (BUN CTR2 = 0, END2 = CTR1 == END1 - 1 ? REPS & CHECK_QRY_TIMEOUT_MASK : CHECK_QRY_TIMEOUT_STEP; CTR2 < END2; CTR2++, IDX++)
2462 :
2463 : /* there is no user-visible loop variable */
2464 : #define TIMEOUT_LOOP(REPEATS, QC) \
2465 : for (BUN CTR1 = 0, REPS = (REPEATS), END1 = (REPS + CHECK_QRY_TIMEOUT_STEP) >> CHECK_QRY_TIMEOUT_SHIFT; CTR1 < END1 && !GDKexiting() && ((QC) == NULL || (QC)->endtime >= 0); CTR1++) \
2466 : if (CTR1 > 0 && TIMEOUT_TEST(QC)) { \
2467 : break; \
2468 : } else \
2469 : for (BUN CTR2 = 0, END2 = CTR1 == END1 - 1 ? REPS & CHECK_QRY_TIMEOUT_MASK : CHECK_QRY_TIMEOUT_STEP; CTR2 < END2; CTR2++)
2470 :
2471 : /* break out of the loop (cannot use do/while trick here) */
2472 : #define TIMEOUT_LOOP_BREAK \
2473 : { \
2474 : END1 = END2 = 0; \
2475 : continue; \
2476 : }
2477 :
2478 : /* check whether a timeout occurred, and execute the CALLBACK argument
2479 : * if it did */
2480 : #define TIMEOUT_CHECK(QC, CALLBACK) \
2481 : do { \
2482 : if (GDKexiting() || ((QC) && (QC)->endtime < 0)) \
2483 : CALLBACK; \
2484 : } while (0)
2485 :
2486 : typedef struct gdk_callback {
2487 : char *name;
2488 : int argc;
2489 : int interval; // units sec
2490 : lng last_called; // timestamp GDKusec
2491 : gdk_return (*func)(int argc, void *argv[]);
2492 : struct gdk_callback *next;
2493 : void *argv[];
2494 : } gdk_callback;
2495 :
2496 : typedef gdk_return gdk_callback_func(int argc, void *argv[]);
2497 :
2498 : gdk_export gdk_return gdk_add_callback(char *name, gdk_callback_func *f, int argc, void
2499 : *argv[], int interval);
2500 : gdk_export gdk_return gdk_remove_callback(char *, gdk_callback_func *f);
2501 :
2502 :
2503 : #include <setjmp.h>
2504 :
2505 : typedef struct exception_buffer {
2506 : #ifdef HAVE_SIGLONGJMP
2507 : sigjmp_buf state;
2508 : #else
2509 : jmp_buf state;
2510 : #endif
2511 : int code;
2512 : char *msg;
2513 : int enabled;
2514 : } exception_buffer;
2515 :
2516 : gdk_export exception_buffer *eb_init(exception_buffer *eb);
2517 :
2518 : /* != 0 on when we return to the savepoint */
2519 : #ifdef HAVE_SIGLONGJMP
2520 : #define eb_savepoint(eb) ((eb)->enabled = 1, sigsetjmp((eb)->state, 0))
2521 : #else
2522 : #define eb_savepoint(eb) ((eb)->enabled = 1, setjmp((eb)->state))
2523 : #endif
2524 : gdk_export _Noreturn void eb_error(exception_buffer *eb, char *msg, int val);
2525 :
2526 : typedef struct allocator {
2527 : struct allocator *pa;
2528 : size_t size;
2529 : size_t nr;
2530 : char **blks;
2531 : size_t used; /* memory used in last block */
2532 : size_t usedmem; /* used memory */
2533 : void *freelist; /* list of freed blocks */
2534 : exception_buffer eb;
2535 : } allocator;
2536 :
2537 : gdk_export allocator *sa_create( allocator *pa );
2538 : gdk_export allocator *sa_reset( allocator *sa );
2539 : gdk_export void *sa_alloc( allocator *sa, size_t sz );
2540 : gdk_export void *sa_zalloc( allocator *sa, size_t sz );
2541 : gdk_export void *sa_realloc( allocator *sa, void *ptr, size_t sz, size_t osz );
2542 : gdk_export void sa_destroy( allocator *sa );
2543 : gdk_export char *sa_strndup( allocator *sa, const char *s, size_t l);
2544 : gdk_export char *sa_strdup( allocator *sa, const char *s);
2545 : gdk_export char *sa_strconcat( allocator *sa, const char *s1, const char *s2);
2546 : gdk_export size_t sa_size( allocator *sa );
2547 :
2548 : #if !defined(NDEBUG) && !defined(__COVERITY__) && defined(__GNUC__)
2549 : #define sa_alloc(sa, sz) \
2550 : ({ \
2551 : allocator *_sa = (sa); \
2552 : size_t _sz = (sz); \
2553 : void *_res = sa_alloc(_sa, _sz); \
2554 : TRC_DEBUG(ALLOC, \
2555 : "sa_alloc(%p,%zu) -> %p\n", \
2556 : _sa, _sz, _res); \
2557 : _res; \
2558 : })
2559 : #define sa_zalloc(sa, sz) \
2560 : ({ \
2561 : allocator *_sa = (sa); \
2562 : size_t _sz = (sz); \
2563 : void *_res = sa_zalloc(_sa, _sz); \
2564 : TRC_DEBUG(ALLOC, \
2565 : "sa_zalloc(%p,%zu) -> %p\n", \
2566 : _sa, _sz, _res); \
2567 : _res; \
2568 : })
2569 : #define sa_realloc(sa, ptr, sz, osz) \
2570 : ({ \
2571 : allocator *_sa = (sa); \
2572 : void *_ptr = (ptr); \
2573 : size_t _sz = (sz); \
2574 : size_t _osz = (osz); \
2575 : void *_res = sa_realloc(_sa, _ptr, _sz, _osz); \
2576 : TRC_DEBUG(ALLOC, \
2577 : "sa_realloc(%p,%p,%zu,%zu) -> %p\n", \
2578 : _sa, _ptr, _sz, _osz, _res); \
2579 : _res; \
2580 : })
2581 : #define sa_strdup(sa, s) \
2582 : ({ \
2583 : allocator *_sa = (sa); \
2584 : const char *_s = (s); \
2585 : char *_res = sa_strdup(_sa, _s); \
2586 : TRC_DEBUG(ALLOC, \
2587 : "sa_strdup(%p,len=%zu) -> %p\n", \
2588 : _sa, strlen(_s), _res); \
2589 : _res; \
2590 : })
2591 : #define sa_strndup(sa, s, l) \
2592 : ({ \
2593 : allocator *_sa = (sa); \
2594 : const char *_s = (s); \
2595 : size_t _l = (l); \
2596 : char *_res = sa_strndup(_sa, _s, _l); \
2597 : TRC_DEBUG(ALLOC, \
2598 : "sa_strndup(%p,len=%zu) -> %p\n", \
2599 : _sa, _l, _res); \
2600 : _res; \
2601 : })
2602 : #endif
2603 :
2604 : #endif /* _GDK_H_ */
|