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