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