Server Programming

Server Programming giulia Mon, 02/24/2020 - 10:55

New functionality can be programmed in SQL, according to the user needs. SQL comes with  imperative programming concepts, such as variable declarations, compound statements, while-loops, and conditional-statements. The are grouped into procedures, functions, and triggers, which strongly differ in their execution paradigm and semantics.

Extending SQL

Extending SQL giulia Mon, 02/24/2020 - 10:58

Under construction

Embedded Python/NumPy

Embedded Python/NumPy giulia Mon, 03/23/2020 - 15:51

Python is one of the most popular languages in Data Science. It is a flexible scripting language that is easy to use and has a large amount of available statistical libraries. When we're doing statistical analysis in Python, we naturally need data accessible to us in Python in some way. And what better place to keep data than in a database.

Previously when you wanted to combine MonetDB and Python, you had to use the Python MAPI client. This client suffers from very low transfer speeds because it uses sockets. If you want to execute Python functions on larger data sets this low transfer speed quickly grows out of control. 

This is why we are now introducing MonetDB/Python, in which we allow users to create their own Python functions as they would create SQL functions. The embedded python functions can then be used within SQL statements. We show that our new method of making data available to Python analyses is faster than competing solutions.

By using Numpy arrays, which are essentially Python wrappers for C arrays, our Embedded Python implementation can transfer data from MonetDB to Python without unnecessarily copying the data, which leads to extremely fast transfer speeds. In addition, Embedded Python supports mapped operations, which allows you to run python functions in parallel within SQL queries. Combined with the numpy/scipy libraries, which contain very efficient C implementations of numerous statistical/analytical functons, Embedded Python matches the speed of native SQL functions, while offering all the flexibility and ease of use of the Python scripting language. In addition, you can load any of the numerous available Python modules and use them.

Embedded Python works by creating a SQL Function that contains the Python code to be run. A simple function that multiplies the input by two is as follows.

    return i * 2

After creating this function, we can use it in a SQL query as follows.

INSERT INTO integers VALUES (1), (2), (3), (4), (5);
SELECT python_times_two(i) AS result FROM integers;

Data Input

Now you might be wondering what exactly "i" is in this function. As we have mentioned previously, we are using Numpy for converting between MonetDB and Python. The exact type of "i" depends on the input; if the input contains a NULL value, "i" will be a MaskedArray, otherwise "i" will be a regular one-dimensional Numpy array. The dtype of the array depends on the type specified in the SQL function. In this example the specified type is "INTEGER", which corresponds to a dtype of numpy.int32. Below is a table that contains the exact types for every possible input value.

INPUT          DTYPE
BOOLEAN        numpy.int8
TINYINT        numpy.int8
SMALLINT       numpy.int16
INTEGER        numpy.int32
BIGINT         numpy.int64
REAL           numpy.float32
FLOAT          numpy.float64
HUGEINT        numpy.float64
STRING         numpy.object [1]

Creating Tables using Python Data

We can also use the embedded python to create tables or insert data into existing tables. Consider the following function.

CREATE FUNCTION python_table() 
    result = dict()
    result['name'] = ['Henk', 'John', 'Elizabeth']
    result['country'] = ['NL', 'USA', 'UK']
    result['age'] = [25, 30, 33]
    return result

This returns a table with three columns. We can then create an actual table in our database as follows.

  SELECT * FROM python_table() 
  WITH data;
SELECT * FROM people;
name country age
Henk NL 25
John USA 30
Elizabeth UK 33

Naturally this is only a toy example that takes no input and simply returns a constant table. Perhaps a more useful example is the following function.

CREATE FUNCTION random_integers(low INTEGER, high INTEGER, amount INTEGER) 
    return numpy.random.randint(low, high, size=(amount,))

This function generates a table with "amount" entries, where each entry is a random integer between low and high. We can then use the function to generate a table of 5 integers with a value between 0 and 10 as follows. 

SELECT * FROM random_integers(0, 10, 5);

Filtering Data

We can use an embedded python function in the WHERE clause to pick which rows to include in the result set. Consider the following function that checks, for every string in a column, if a given string (needle) is a part of that string (haystack).

CREATE FUNCTION python_strstr(strings STRING, needle STRING) 
    return [needle in haystack for haystack in strings]

We can now use this function to select all people with the letter 'n' in their name.

SELECT * FROM people WHERE python_strstr(name, 'n');
name country age
Henk NL 25
John USA 30

Aggregating Data

Finally, we can use an embedded python function for computing aggregates. The syntax for creating an aggregate is as follows.

CREATE AGGREGATE python_aggregate(val INTEGER) 
        unique = numpy.unique(aggr_group)
        x = numpy.zeros(shape=(unique.size))
        for i in range(0, unique.size):
            x[i] = numpy.sum(val[aggr_group==unique[i]])
    except NameError:
        # aggr_group doesn't exist. no groups, aggregate on all data
        x = numpy.sum(val)

This is a simple aggregate that sums the integers for each group or when no groups are defined for all values. We can then use the aggregate just as we would use a SQL aggregate.

CREATE TABLE grouped_ints(value INTEGER, groupnr INTEGER);
INSERT INTO grouped_ints VALUES (1, 0), (2, 1), (3, 0), (4, 1), (5, 0);
SELECT groupnr, python_aggregate(value) FROM grouped_ints GROUP BY groupnr;
groupnr L1
0 9
1 6

As you can see, this produces output equivalent to the SQL statement SUM(). If you look at the source code you will see the usage of a hidden parameter "aggr_group". Note that parameter "aggr_group" is only created when a GROUP BY is used in the SQL query. This parameter is passed to aggregates and contains a numpy array of the group numbers for each tuple. In the above example, aggr_group contains the numbers [0, 1, 0, 1, 0]. We then use the group numbers of each tuple to compute the aggregate value for each group.

Note also that aggr_group will always be a one dimensional array containing the group numbers, even if we do a GROUP BY over multiple columns, as in the below example.

CREATE TABLE grouped_ints(value INTEGER, groupnr INTEGER, groupnr2 INTEGER);
INSERT INTO grouped_ints VALUES (1, 0, 0), (2, 0, 0), (3, 0, 1), (4, 0, 1), (5, 1, 0), (6, 1, 0), (7, 1, 1), (8, 1, 1);
SELECT groupnr, groupnr2, python_aggregate(value) FROM grouped_ints GROUP BY groupnr, groupnr2;
groupnr groupnr2 L1
0 0 3
0 1 7
1 0 11
1 1 15

MonetDB transparently handles multiple groups for aggregates. In this example aggr_group will be a single array containing the values [0, 0, 1, 1, 2, 2, 3, 3].

Parallelized Execution of Python Functions

When performing a SQL query, MonetDB can speed up the query by splitting up the columns and running the query in parallel on multiple threads when possible. This is a process called mitosis. For example, when we want to take the square root of every element of a column, we can split up the column and have separate threads work on separate parts of the column. This is shown in the image below for a column of size 4 being split into two parts, and having two threads execute the operation.

However, certain operations cannot be parallelized because they require access to the entire column. These are called blocking operations. An example of such a blocking operation is the quantile function, because we cannot compute the quantile of a column when we only have access to part of a column. By default, embedded python is a blocking operation. This is because it is very easy to write a user defined function that is not mappable. We could, for example, use our python function to compute a quantile.

However, blocking operations are inefficient. When we use a blocking operation, we need to wait for all the previous threads to finish their operations. Then, we need to take all the split-up columns and recombine them into one big column, and then we can finally call the blocking operation. If our python function is mappable, we would prefer it to be executed in parallel.

Well, good news! We support this. If you know that your function is mappable, you can specify this by setting the LANGUAGE to PYTHON_MAP instead of PYTHON when creating the SQL function. Your function is mappable if the output does not depend on the entire column, but only on the individual rows.

For a simple example, let's go back to the first function we created: multiplying a column of integers by 2. This is a mappable function, as the output works with the individual rows. The new function looks like this.

    return i * 2

We can then use it just as we used the regular python_times_two function, and it will return the same result.

SELECT python_times_two_map(i) AS result FROM integers;

Even for such a simple function we can see a big performance increase when we increase the input size. Below is a graph running both functions with 1GB of input data.

Note that it is possible to run non-mappable functions using LANGUAGE PYTHON_MAP, however, this will then naturally produce different output than running the same function with LANGUAGE PYTHON. It is possible to abuse this to run part of a Python function in parallel. As an example, let's make the MIN() function in our embedded Python.

Suppose we have the following mapped function, and the following non-mapped function.

    return numpy.min(i)
    return numpy.min(i)

At a glance these functions look identical. If we run the following query we will get the expected result.

SELECT python_min(i) FROM integers;

But if we run the mapped query we will get a different result [2]. 

SELECT python_min_map(i) FROM integers;

Since we are running with two threads, the function python_min_map is being executed twice. Once for one part of the column, and once for another part of the column. This means that the function returns two separate values. We can obtain the actual minimum value by using our sequential function python_min on the result of python_min_map.

SELECT python_min(python_min_map(i)) FROM integers;

Now part of our query is being run in parallel, and we are still obtaining the desired result. Running these functions for a data set of 1000MB we can see that our parallel function has better performance than simply calling python_min, while still computing the correct value.


To keep in with tradition, we will use embedded python to compute quantiles. We can do this efficiently using the numpy.percentile function. We will compare our embedded Python implementation against various other ways of loading data into Python and then executing the numpy.percentile function on the data, as well as some other non-Python ways of computing the quantile. In our example, we are using a single table containing 1 GB of integer values (250M values). 

  • MonetDB/Python: This is our implementation, using numpy.percentile on the data within a MonetDB table. MonetDB uses memory mapping to load the data into memory very quickly, and because of our zero-copy transfer into Python there is no additional overhead cost for transferring this data into Python. 
  • MonetDB C UDF: Compute the quantile in MonetDB using a C UDF. We computed the quantile using Quickselect.
  • NumPy Binary: Use numpy.load() to load the data into a numpy array from a numpy binary file. This is a very fast way of loading data into Python, because we are directly mapping a binary file into memory we do not have to do any decoding.
  • NumPy MemoryMap: Use numpy.memmap() to load the data into a numpy array from a numpy binary file. This has similar performance to NumPy binary files.
  • PyTables: Load the data using tables.open_file(). This is fast because it loads a binary file directly into a Numpy array.
  • PyFITS: Use to load the data from into a numpy array from a .fits file.
  • castra: A column-store database created entirely in Python.  This uses Python pickling to load the database file as a Python object from an encoded string. This has some additional overhead. 
  • MonetDB/R: Using the MonetDB/R plugin, using the native R quantile function instead of the numpy.percentile function. The MonetDB/R extension does not use zero-copy transferring, which means there is extra overhead of copying the data once. In addition, it seems the numpy.percentile() function is faster than the quantile() function in R.
  • Monary: Monary is a connector for MongoDB that is optimized for use with NumPy
  • MonetDB Built-In: Use the built-in SQL quantile() function in MonetDB. This function does not use a very efficient algorithm for computing the quantile, which is why it takes a while.
  • PandasCSV: Use the read_csv() function from the pandas library to load the data. This is an efficient C implementation of a CSV loader. However, we still need to decode the CSV and convert it into integer values, which means the loading takes a while.
  • Psycopg2: Load the data into Python using psycopg2, the default Python connector for Postgres, and then use numpy.percentile() to compute the quantile. This is slow because it constructs individual Python objects for every integer.
  • PL/Python: Load the data from a Postgres table using plpy.cursor() in a PL/Python function. This is slow because it loads the data as Python objects. There is also additional overhead from Postgres having to first gather all the relevant integer into a single array, as it is a row store database.
  • SQLite: Call 'SELECT * FROM table' to load the data from SQLite into Python, using the built-in sqlite3 module. This implementation uses Python objects for integers instead of Numpy arrays, which carry a lot of additional overhead with regards to loading as we have to construct 250 million Python integer objects (which each have to be malloc'd individually).
  • Postgres Built-In: Perform the quantile computation using the built-in percentile_cont aggregate, with Postgres tuned for Data Warehousing using pgtune. 
  • CSV: Use the built-in Python csv library to load the data into a Numpy array. This is much less efficient than the pandas load_csv() library as it constructs Python objects. In addition, the CSV loader is written in pure Python which carries additional overhead. 
  • MonetDB MAPI: Use the current MonetDB Python client to load the data into Python. This is extremely slow because data has to be serialized over sockets. 
  • MySQL Cursor: Load the data into Python using the MySQL Python Connector. This is extremely slow because it sends the data to Python one row at a time.


We have shown that our embedded Python implementation is fast, however, the true strength of using Python is the fact that it is so flexible. All the functions we have shown here can easily be implemented in SQL as well.

In the next blog post we demonstrate that MonetDB/Python can be used for much more than just emulating simple SQL functions by performing classification, including preprocessing, training and predicting, of a big dataset using MonetDB/Python combined with SQL, without the data ever leaving MonetDB. This blog post can be found here.

We would like to make this integration generally available with the next feature release of MonetDB, till then we really would appreciate feedback at .


Currently MonetDB/Python is available in the in-development version of MonetDB in the default branch and must be compiled from source. Note that you will need NumPy installed for embedded python to work. You can look here for information on how to install NumPy. To compile the pythonudf branch from scratch, you can download a tar file of the source here. You can then compile the source by running the following commands in the root directory of the source tree.

./configure --prefix=<install_directory>
make install

You can then run MonetDB by starting the monetdbd daemon or mserver5 in the given installation directory. Note that you will need to explicitly enable Python integration using the following commands if you are using the monetdbd daemon.

monetdb stop pytest
monetdb set embedpy=true pytest
monetdb start pytest

Or the following command if you are running mserver5.

mserver5 --set embedded_py=true

You can then connect to MonetDB and use embedded python.

About the Author

Mark Raasveldt is studying Computer Science at Utrecht University. He is currently working on his Master's thesis at the CWI Database Architectures Group. Surprisingly, he is working on embedding Python in MonetDB.


[1] The Numpy array is filled with Python objects of either type 'str' (if there are no unicode characters in the column) or 'unicode' (if there are unicode characters in the column).

[2] Note that we are running with 2 threads and forcing mitosis (mserver5 flags --set gdk_nr_threads=2 --forcemito). --forcemito forces mitosis on small tables, otherwise MonetDB would not split up a table of 5 entries.

Embedded R

Embedded R giulia Mon, 03/23/2020 - 15:56

For some time now, we have had the MonetDB.R package on CRAN, which allows you to connect to a MonetDB server from an R session. This package uses the MAPI protocol to talk to MonetDB over a standard socket. In addition to running queries, the package also supports the more high-level dplyr API. 

While we worked hard on making this integration as painless as possible, there was one issue that we could not solve: Processing data from the database with R required transferring the relevant data over the socket first. This is fine and "fast enough" for  up to – say – several thousand rows, but not for much more. We have had a lot of demand for transferring larger amounts of data from users. Hence, we chose to go in a different direction. 

Starting with the Oct2014 release, MonetDB will ship with a feature we call R-Integration. R has some support for running embedded in another application, a fact we leverage heavily. What it does is make R scripts a first class citizen of the SQL world in MonetDB. Users can create ad-hoc functions much in the style of SQL functions. In the remainder of this blog post, we will describe the installation, the usage and some initial performance observations of RIntegration.


R-Integration works by wrapping R code in an SQL function definition, so that the SQL compiler knows the input and output schema of the function. R functions can be used in various parts of an SQL query, for instance, as table-producing functions (used in the FROM clause), as projection functions (used in the SELECT clause), as filtering functions (used in the WHERE clause) and as aggregation functions (also in the SELECT clause, but together with a GROUP BY clause). 

We begin with a table-producing function


In this example, there are no parameters going into the function, but it returns a table with a single integer-typed column. Inside the curly braces we see the function body, which is plain R code. This function generates the sequence of numbers from 1 to 10. If we want to call it, we can do so from the SQL prompt:

SELECT d FROM rapi00() AS r WHERE d > 5;

Here, the R function takes the FROM position in the query. Note how we filter the output by only selecting values greater than 5. The output of this function is

sql>SELECT d FROM rapi00() AS r WHERE d > 5;
| d    |
|    6 |
|    7 |
|    8 |
|    9 |
|   10 |

Here is a slightly more complicated example with a constant input parameter and two output columns:

    data.frame(i=seq(1, i), d=42.0);

Note how we can use the SQL input parameter inside the R code. It will be automatically translated into the R world. Also note how we construct a to return the two-column result SQL expects. An example invocation and result would be

sql>SELECT i, d FROM rapi01(42) AS R WHERE i > 40;
| i    | d                        |
|   41 |                       42 |
|   42 |                       42 |

For the remaining examples, let's create some sample data:

INSERT INTO rval VALUES (42),(43),(44),(45);
CREATE TABLE rvalg(groupcol INTEGER, datacol INTEGER);
​INSERT INTO rvalg VALUES (1, 42), (1, 84), (2, 42), (2, 21);

The following R function will multiply the passed values. We can use it to do some computations on the projected columns in an SQL query:


In this example, we will call this function with a constant as the second parameter:

sql>SELECT rapi02(i, 2) FROM rval;
| rapi02_i |
|       84 |
|       86 |
|       88 |
|       90 |

We can also use the R functions in the WHERE clause of the query, where they can decide whether a row is included in the result or not:

sql>SELECT * FROM rval WHERE rapi03(i, 44);
| i    |
|   45 |

Finally, we can use an R function to calculate an aggregation within the projection of a GROUP BY query:

    aggregate(val, by=list(aggr_group), FUN=median)$x

Note the keyword AGGREGATE and the magical R variable aggr_group, which contains an integer number denoting which group a row belongs to. If we run this function, we get the following result

sql>SELECT groupcol, rapi04(datacol) FROM rvalg GROUP BY groupcol;
| groupcol | L1                       |
|        1 |                       63 |
|        2 |                     31.5 |

As a final note on usage, you can use any R package from CRAN within your function without explicitly installing it. We overloaded the library function in R to automatically install missing packages.


Since we no longer need to serialize data onto a socket with our new solution, we expect great performance benefits. Also, since both MonetDB and R use a columnar data layout, little effort has to be spent on converting the values between these two systems. In fact, we have shown how we can gain a zero-copy integration between MonetDB and R in prototypical work. In the released version however, we invest one in-memory copy of the data for increased peace of mind. For this experiment, we have used the lineitem table of the well-known TPC-H benchmark at scale factor 100. This table contains 100 million rows. The test task was to calculate the .05 and .95 quantiles of the l_extendedprice column. The contenders in the benchmark were 

  • MonetDB itself, we have added quantile support some time ago (MonetDB)
  • R using the MonetDB.R socket connector, retrieving all columns, then calculate quantiles (R-full)
  • R using the MonetDB.R socket connector, retrieving a single column, then calculate quantiles (R-col)
  • PL/R, the R integration into PostgreSQL, initial approach (PL/R-naive)
  • PL/R, the R integration into PostgreSQL, tuned after feedback from Joe Conway (PL/R-tuned)
  • MonetDB with embedded R (RInt)

All experiments were run on a desktop-class machine with 16 GB of main memory and a 8-core Intel i7 processor. We tuned PostgreSQL using the pgtune utility for analytical workloads. We ran the aggregation over an increasing number of rows, from 1.000 to 100.000.000. All queries were repeated five times for each system and then averaged. The results are given below:

Performance Comparision

In this plot, we can see that R-Integration delivers superior performance to all other solutions, curiously also that of MonetDB's quantile implementation. The reason for this is that R uses partial sorting for its quantile implementation, whereas MonetDB does a full sorting pass over the data to calculate quantiles. Missing data points are due to timeouts (60 seconds limit) or crashes.

For reference, we used the following R UDF for the winning system in this experiment:

CREATE AGGREGATE rquantile(arg1 double, arg2 double) RETURNS double LANGUAGE R { quantile(arg1, arg2) };

This was then run using the SQL query

select rquantile(cast(l_extendedprice as double), 0.05) as q5, rquantile(cast(l_extendedprice as double), 0.95) as q95 from lineitem;


For now, R-Integration is not shipped with the binary distributions of MonetDB due to compatibility and security concerns, Hence, you need to compile MonetDB from source with (just a few) custom parameters. In addition, you need to install an R version (or compile from source, too) that includes the R shared library. On Linux systems, you can check whether you have a file named If you have installed R using your OS's package manager, it will most likely be the case. Compiling MonetDB from source is not hard. To enable R-Integration, you need to run the ./configure script as follows:

./configure --enable-rintegration=yes

If all goes well, the output will contain the following line in the summary at the end

rintegration is enabled 

If not, check that the R binary is in your $PATH, and that R was configured with the --enable-R-shlib=yes flag. You may also be required to set the $LD_LIBRARY_PATH variable to include the path to before starting MonetDB.


After R-Integration has been compiled into the MonetDB installation, you need to explicitly enable it during server startup. If you are using the monetdbd daemon, you can enable R-Integration as follows

monetdb stop rtest
monetdb set embedr=true rtest
monetdb start rtest

Where rtest is the name of your database. If you are running mserver5 directly, the parameter name is different:

mserver5 --set embedded_r=true

In the latter case, you will see MonetDB's startup message. If you see no error messages and

# MonetDB/R   module loaded

all is well.

MonetDBLite for Java

MonetDBLite for Java giulia Mon, 03/23/2020 - 16:00

Following the footsteps of MonetDBLite for R and MonetDBLite for Python, we now have MonetDBJavaLite which deploys MonetDBLite in a JVM with JDBC support. It has been tested on Linux, Mac and Windows. In the "lite" versions of MonetDB, both client and server run within the same process, saving eventual inter-process communication such as a socket connection. Although the code is still somewhat experimental, it’s worth trying out, and report your stories and complains.

MonetDBJavaLite connections

We provide two APIs for MonetDBJavaLite: an Embedded API (non-standard) and the standard JDBC API. The former API has been introduced for certain scenarios where performance is critical, such as when dealing with large result sets. But the better performance comes at the cost of less portability. The Javadoc of this API can be found in our website.

A MonetDBLite JDBC connection is very similar to a regular connection with a MonetDB server. Differences between the two connections are:

  • Only one database is allowed per JVM process. However multiple connections to the same database is allowed within the same process.
  • MonetDBLite is a compacted version of MonetDB with some features removed in order to reduce  the size of the library, e.g. the GEOM  module, MERGE TABLE  and REMOTE TABLE, the JSON module, and the Data Vaults extension.
  • The authentication scheme is absent from MonetDBLite.
  • MonetDBJavaLite native code uses a separate heap from the JVM, which means that connections and result sets descriptions must be explitily closed to avoid memory leaks.
  • No two concurrent MonetDBJavaLite processes can use the same database farm simultaneously.

Embedded API

Start a database

A database must be started before any connection can be made. When starting the database, one can specify a path to the database farm. If no such path is supplied, an in-memory connection will be automatically established instead. In an in-memory connection data is not persisted on disk. In other hand transactions are held in-memory thus more performance is obtained.

Path directoryPath = Files.createTempDirectory("testdb");
//start the database with the silent flag set (no debugging output) and disable the sequential pipeline.
MonetDBEmbeddedDatabase.startDatabase(directoryPath.toString(), true, false);
MonetDBEmbeddedConnection connection = MonetDBEmbeddedDatabase.createConnection();
connection.executeUpdate("CREATE TABLE example (words text)");
MonetDBEmbeddedDatabase.stopDatabase(); //Don’t forget to shutdown at the end :)


After a connection has been established, one can send  queries to the embedded database and retrieve the results. The connection starts on the auto-commit mode by default. The methods void startTransaction(), void commit() and void rollback() can be used for transaction management. The methods Savepoint setSavepoint(), Savepoint setSavepoint(String name), void releaseSavepoint(Savepoint savepoint) and void rollback(Savepoint savepoint) handle savepoints in transactions.

Update queries

For update queries (e.g. INSERT, UPDATE and DELETE), the method int executeUpdate(String query) is used to send update queries to the server and get the number of rows affected.

int numberOfInsertions = connection.executeUpdate("INSERT INTO example VALUES ('monetdb'), ('java'), (null)");

Queries with result sets

For queries with result sets, one can use the method QueryResultSet executeQuery(String query) to send a query to the server, and retrieve the results using a QueryResultSet instance.

The result set metadata can be retrieved with the methods int getNumberOfRows(), int getNumberOfColumns(), void getColumnNames(String[] input) and void getColumnTypes(String[] input).

There are several ways to retrieve the results of a query. The family of methods T get#TYPE#ByColumnIndexAndRow(int column, int row) and
T get#TYPE#ByColumnNameAndRow(String columnName, int row) retrieve a single value from the result set. The column and row indexes for these methods (and the other methods in this family) start from 1, same as  in JDBC.

A column of values can be retrieved using the family of methods void get#TYPE#ColumnByIndex(int column, T[] input, int offset, int length) and void get#TYPE#ColumnByName(String name, T[] input, int offset, int length). Note  that the input array must be initialized beforehand. If there is no desire to provide the offset and length parameters, the methods void get#Type#ColumnByIndex(int column, T[] input) and get#Type#ColumnByName(String columnName, T[] input) can be used instead.

QueryResultSet qrs = connection.executeQuery("SELECT words FROM example");
int numberOfRows = qrs.getNumberOfRows();
int numberOfColumns = qrs.getNumberOfColumns();
String[] columnNames = new String[numberOfColumns];
qrs.getColumnNames(columnNames); //returns ['words']

String singleWord = qrs.getStringByColumnIndexAndRow(1, 1); //gets 'monetdb'
String[] wordsValues = new int[numberOfRows];
qrs.getStringColumnByIndex(1, wordsValues); //returns ['words', 'java', null]
qrs.close(); //Don’t forget :)

To check if a boolean value is NULL, one can use the method boolean checkBooleanIsNull(int column, int row) of the class QueryResultSet. For all other data types, one can use the methods boolean Check#Type#IsNull(T value) of the class NullMappings.

Append data to a table

To append new data to a table, one can use the method int appendColumns(Object[] data) from the class MonetDBTable. The data should come as an array of columns, where each column has the same number of rows, and each array class corresponds to the mapping defined above. To insert null values, use the constant T get#Type#NullConstant() from the class NullMappings.

connection.executeUpdate("CREATE TABLE interactWithMe (dutchGoodies text, justNumbers int)");
MonetDBTable interactWithMe = connection.getMonetDBTable("interactWithMe");
String[] goodies = new String[]{"eerlijk", "lekker", "smullen", "smaak", NullMappings.getObjectNullConstant<String>()};
int[] numbers = new int[]{2, 3, NullMappings.getIntNullConstant(), -1122100, -23123};
Object[] appends = new Object[]{goodies, numbers};

Data type mapping

The Java programming language is a strong typed language, thus the mapping between MonetDB SQL types and Java classes/primitives must be explicit. The usage of Java primitives is favored for the most common MonetDB SQL types, hence making less object allocations. However for the more complex SQL types, such as Strings and Dates, the map is made to Java Classes, while matching the JDBC specification.

One important feature of MonetDB is that the SQL NULL values are mapped into the system's minimum values. In MonetDBJavaLite, this feature persists for primitive types. NB: for the Java Classes mapping, SQL NULL values are translated into null objects! Other more rare data types such as geometry, json, inet, url, uuid and hugeint are missing. These types were removed from MonetDBLite to reduce the size of the library. Please check the GitHub documentation for details on data type mapping.

Other methods provided in this API include Prepared Statements which are detailed in the GitHub documentation and the Javadocs.


To start a JDBC embedded connection, one must provide a JDBC URL in the format: jdbc:monetdb:embedded:[<directory>], where directory is the location of the database. To connect to an in-memory database the directory must be :memory: or not present.

When starting a JDBC Embedded connection, it checks if there is a database instance running in the provided directory, otherwise an exception is thrown. While closing, if it's the last connection, the database will shut down automatically.

//Connection con = DriverManager.getConnection("jdbc:monetdb:embedded:/home/user/myfarm"); //POSIX
//Connection con = DriverManager.getConnection("jdbc:monetdb:embedded:C:\\user\\myfarm"); //Windows
//Connection con = DriverManager.getConnection("jdbc:monetdb:embedded::memory:"); //in-memory mode
Statement st = con.createStatement();
st.executeUpdate("CREATE TABLE jdbcTest (justAnInteger int, justAString varchar(32))");
st.executeUpdate("INSERT INTO jdbcTest VALUES (1, 'testing'), (2, 'jdbc')");
ResultSet rs = st.executeQuery("SELECT justAnInteger, justAString from test1;");
while ( {
    int justAnInteger = rs.getInt(1);
    String justAString = rs.getString(2);
    System.out.println(justAnInteger + " " + justAString);
rs.close(); //Don't forget! :)

Please check the GitHub documentation for differences between MonetDB’s JDBC socket and embedded connections.


The project is hosted and maintained on Github:

Two JAR files are distributed: monetdb-java-lite (~6.4Mb) and monetdb-jdbc-new (~150Kb). The former depends on the later and contains MonetDBLite library adapted for the JVM. It is compatible with JVM 8 onwards only. This JAR also provides native libraries for 64-bit Linux, MacOS X and Windows. The later is a fork of MonetDB’s JDBC driver and is used for JDBC connections.

Both JARs are hosted on Maven Central repository.

  • Apache Maven:
  • Gradle: compile 'monetdb:monetdb-java-lite:2.33'

Otherwise is possible to download the JARs from our website and add them to the CLASSPATH.

Developer and support

MonetDBJavaLite is being supported by Pedro Ferreira, a software developer at MonetDB Solutions. Feel free to sign up and send your questions to the MonetDB users-list.

User Defined Functions

User Defined Functions giulia Mon, 05/04/2020 - 17:38

An open source solution provides a stepping stone for others to extend its kernel functionality with specific types and functions. Experience shows that the need for those are fairly limited. Often the use of the built-in data types, the MAL algebra and functional abstraction, provide the necessary toolkit to achieve your goal.

In the few cases where the MonetDB kernel and SQL runtime system needs extensions, it calls for access to the source code of MonetDB and proficiency in C-programming, compilation and debugging. The openess of MonetDB means that extensions are not sand-boxed; they run within the system address space. Moreover, the multi-layered architecture means you have to make the functions written in C known to the MAL interpreter, before they can be made known to the  SQL compiler. The current setup makes this a little more cumbersome, but the added benefit is that both simple scalar functions and columnar operations can be introduced.

In this section we show how to extend SQL with a simple scalar function to reverse a string, i.e.

sql> select 'hello',reverse('hello');
| hello | olleh |

step 1. You should access and be able to compile and install MonetDB in a private directory.

step 2. Go to the sql/backends/monet5/UDF directory from the sources top directory. It provides the reverse example as a template. A group of user-defined functions is assembled in a directory like UDF. It contains files that described the SQL signature, the MAL signature, and the C-code implementation.

step 3. Extension starts with a definitin of the MAL signatures. See the example given, or browse through the files in monetdb5/modules/mal/*.mal to get a glimpse on how to write them. The MonetDB kernel documentation provides more details.  The file contains the MAL snippet:
command reverse(ra1:str):str
address UDFreverse
comment "Reverse a string";

step 4. The signature says that it expects a command body implementation under the name UDFreverse, shown below. The C-signature is a direct mapping, where arguments are passed by reference and the return value(s)  references are the first in the arguments list. The body should return a (malloced) string to denote an exception being raised or MAL_SUCCEED upon access.
#include "udf.h"

static str
reverse(const char *src)
    size_t len;
    str ret, new;

    /* The scalar function returns the new space */
    len = strlen(src);
    ret = new = GDKmalloc(len + 1);
    if (new == NULL)
        return NULL;
    new[len] = 0;
    while (len > 0)
        *new++ = src[--len];
    return ret;

UDFreverse(str *ret, str *src)
    if (*src == 0 || strcmp(*src, str_nil) == 0)
        *ret = GDKstrdup(str_nil);
        *ret = reverse(*src);
    return MAL_SUCCEED;

step 5. The next step is to administer the routine in the SQL catalog. This calls for a SQL statement to be executed once for each database. The autoload method can relieve you from loading the modules manually in the server after each restart. The UDF template contains the file 80_udf.sql and 80_udf.mal. The former contains the definition needed for SQL:
create function reverse(src string)
returns string external name udf.reverse;

step 6. The MAL interpreter should be informed about the linked in functionality. This is faciliated using an autoload feature too. The MAL script  simply contains the module signature.

include udf;

step 7. After all pieces are prepared, you have to call the bootstrap program in the root of your checked out source tree once. Thereafter a configure/make/make install attempts compilation and places the interface files and libraries in the proper place.

Creation of bulk  and polymorphmic operations require much more care. In general, it is best to find an instruction that is already close to what you need. Clone it, expand it, compile it, and test it.  A bulk variation of the reverse operation is included in the sample UDF template. As a last resort you can contact us on the mailing lists for further advice.

Rule System

Rule System giulia Mon, 02/24/2020 - 11:11

Under construction


Triggers giulia Mon, 02/24/2020 - 11:00

Triggers are a convenient programming abstraction. They are activated at transaction commit based on updates to the base tables.

trigger_def: CREATE [ OR REPLACE ] TRIGGER qname  trigger_action_time  trigger_event  ON  ident  opt_referencing_list  triggered_action

trigger_action_time: BEFORE | AFTER

trigger_event: INSERT | DELETE | TRUNCATE | UPDATE | UPDATE OF ident ','...

opt_referencing_list: [ REFERENCING old_or_new_values_alias ... ]

      OLD [ ROW ] [ AS ] ident
    | NEW [ ROW ] [ AS ] ident
    | OLD TABLE [ AS ] ident
    | NEW TABLE [ AS ] ident

     opt_for_each [ WHEN search_condition ] triggered_statement

opt_for_each: /* default is for each statement */ | FOR EACH ROW | FOR EACH STATEMENT

   | BEGIN ATOMIC trigger_procedure_statement_list END

   | declare_statement
   | set_statement
   | control_statement
   | select_statement_single_row

Example The following example provides a glimpse of their functionality:

create table t1 (id int, name varchar(1024));
--test FOR EACH STATEMENT (default one)
insert into t1 values(10, 'monetdb');
insert into t1 values(20, 'monet');
create trigger test5
after update on t1
for each statement
when id >0 insert into t1 values(4, 'update_when_statement_true');

All trigger definitions are considered together at the transaction commit. There is no a priori defined order in which they run. Each may in turn activate new triggers, but each trigger definition is also executed only once per transaction commit.