qSQL on DuckDB tables and parquet files¶
Requires a PeachQ download with DuckDB
DuckDB features need a PeachQ package that includes DuckDB. On the download page, choose Download with DuckDB for Windows, macOS or Linux. The standard packages do not include DuckDB.
PeachQ runs qSQL on data it did not write: a table created in DuckDB by SQL, a DuckDB view, a parquet file written by
Spark, pandas, Polars or DuckDB, or a whole hive-partitioned directory of them. This page calls those foreign
tables. A q name bound to a DuckDB table or view with get, such as quotes:get `:pq:duckdb:main:quotes/, is an
external table: the data stays in DuckDB, and the name works in qSQL like a table. A table q wrote, to DuckDB with set or to parquet with .parquet.write, is a q table: it carries its q
types and reads back exactly as written, and nothing on this page changes that.
A foreign table has no q types of its own, so PeachQ gives every column one fixed q type by its DuckDB type. The same table always reads in the same shape, whatever its rows hold.
Point at the data¶
q)select from `:pq:duckdb:main:trades/ where date=2024.01.02 / a DuckDB table or view
q)select px, sym from `:data/day.parquet where sz>100 / one parquet file
q)select from `$":data/quotes/**/*.parquet" where region like "EU" / a glob; DuckDB finds hive partitions
q).parquet.read[`:data/a.parquet`:data/b.parquet;();()] / an explicit list, read in the order given
q).parquet.read[`$":data/quotes/**/*.parquet"; (enlist `hive_partitioning)!enlist 1b;
parse "select last px by sym from t where sym=`A, date within 2024.01.01 2024.01.31"]
PeachQ keeps what it learns about a local file (its columns and types) while the file is unchanged, so a repeated query sends DuckDB one statement. To give a set of files a name, make a DuckDB view once:
q)c:.duckdb.main[]
q).duckdb.exec[c;"CREATE VIEW quotes AS SELECT * FROM read_parquet('data/quotes/**/*.parquet', hive_partitioning=true)"]
q)quotes:get `:pq:duckdb:main:quotes/ / an external table bound to the view
q)select max px by sym from quotes where date=2024.01.02
An external table like quotes is a pointer to the DuckDB table, not its rows. qSQL runs on it, but q verbs that need
the rows themselves (`sym xkey quotes, 1!quotes, t lj quotes) answer 'type. That is deliberate: say which
rows you want first, ref:select from quotes where ..., then key or join the q table that select returns.
How each column reads¶
| DuckDB type | q type | notes |
|---|---|---|
| BIGINT, INTEGER, SMALLINT | j i h |
|
| TINYINT, USMALLINT, UINTEGER | h i j |
widened, so exact |
| DOUBLE, FLOAT | f e |
±inf reads as 0w/-0w |
| BOOLEAN | b |
|
| UTINYINT | x |
|
| VARCHAR | string (C) |
never a symbol; see below |
| DECIMAL | f |
a float: up to about 15 significant digits are exact |
| DATE | d |
|
TIMESTAMP, _S, _MS, _NS |
p |
outside q's range reads as 0Wp / -0Wp |
| TIMESTAMP WITH TIME ZONE | p |
the UTC instant; the offset is not kept |
| TIME, TIME_NS | n |
a timespan since midnight, so microseconds are kept |
| UUID | g |
|
| ENUM | s |
|
| BLOB | X |
|
| BIT | B |
|
| LIST of any of these | a list column | |
| HUGEINT, UBIGINT, UHUGEINT, BIGNUM, INTERVAL, TIME WITH TIME ZONE, STRUCT, MAP, UNION, JSON, GEOMETRY, untyped NULL | hidden | not in cols, meta or select from |
.duckdb.hidden[h;t]and.parquet.hidden[file;opts]list the hidden columns.his the handle of the database
that holds the table:.duckdb.main[]for a table in the main database, or the handlehopengave you
for an attached file (``h:hopen (:pq:duckdb:ref;"ref.duckdb"); .duckdb.hidden[h;`instruments]``). SQL still reaches them, so cast
one into a type q holds when you need it:
To see everything that does not read exactly, ask the inspector. .duckdb.inspect[h;t]and.parquet.inspect[file;opts]` answer one row per column and issue, counted by DuckDB in one statement, so no row
comes back to q:
q).duckdb.inspect[c;`inst]
| col | dtype | qtype | issue | rows |
| symbol | | char | symbol | long |
|----------|-------------|-------|---------|------|
| notional | "HUGEINT" | | hidden | |
| sym | "VARCHAR" | C | merged | 2 |
| qty | "INTEGER" | i | minimum | 1 |
| valid_to | "TIMESTAMP" | p | range | 2 |
The issues are hidden (no q type), range (a timestamp outside q's range, read as 0Wp or -0Wp), minimum
(an integer type's lowest value, read as null), merged (NULL beside '', NaN, the zero UUID or an empty BLOB,
which read as one value), zero (a NULL boolean or byte, read as 0b or 0x00), digits (a DECIMAL wider than
15 digits whose value a float does not hold) and offset (a TIMESTAMP WITH TIME ZONE). rows counts the rows each
issue touches. A table or file q wrote answers an empty table.
The rules¶
- One q type per DuckDB type, as in the table above, applied the same way on every path.
- Nulls merge. A SQL NULL and a value that is a q null in that type (the integer minimum, NaN) both read as the
q null. A NULL string reads as
"", a NULL boolean as0b, a NULL byte as0x00, a NULL list as an empty list. There are no extra columns. When you need to tell a NULL from a real minimum, ask DuckDB in SQL, or count where it happens with the inspector. - Columns q cannot hold are hidden, so
cols,metaandselect fromalways work. A timestamp q cannot hold reads as the infinity on its side, so a select over it answers, and a filter DuckDB runs keeps the rows q would..duckdb.inspectand.parquet.inspectsay where any of this happens. - Text is a string that also answers to symbols. On a foreign table,
sym=`A,sym in `A`Bandsym like "A*"work on a string column, where q itself would signal'typefor the symbol, and`$symgives you symbols in the result. A string literal means what it means in q:sym="A"compares character by character, so writesym=`A,sym like "A"orsym~\:"A"for the whole string. - Row order is not promised.
i,first,lastandselect[n]answer from whatever order the rows arrive in, as a partitioned kdb database does. PeachQ uses a row number when DuckDB has one (a table'srowid, a file's row number, the order of an explicit file list), but do not rely on it; a view has none. - A query answers as if the columns it reads were read into q first and the qSQL run there. PeachQ runs as much of it inside DuckDB as gives the same answer, so only the columns and rows you need come back. A part DuckDB cannot run the same way is run by q, on the rows DuckDB returned.
- Round trips are exact through the pair.
.duckdb.getxanswers(data;schema), and.duckdb.setof that pair writes every column and value back exactly, hidden types and decimals included. The copy is a q table, so it also carries q's row index, a columni.
Gotchas¶
Types and values
- Strings, not symbols. A text column is a string column because PeachQ cannot know in advance how many distinct
values it holds, and interning a column of order ids would fill the symbol table. Cast in the select when you want
symbols:
select `$sym, px from t. ""and NULL are the same string.where sym like ""matches both. So are the integer minimum and NULL, and NaN and NULL. Use SQL to separate them:.duckdb.exec[c;"SELECT count(*) FROM t WHERE qty = -2147483648"].- Decimals are floats. A DECIMAL(38,10) notional loses digits past about 15 significant figures, and a
sumcan differ from DuckDB's exact decimal sum in the last bits. Writing the result back makes a DOUBLE column, not a DECIMAL; use the.duckdb.getxpair for an exact copy. - TIME is a timespan, not a
t. It shows as0D09:30:00.123456000;date+timegives a timestamp. - A NULL boolean is
0b. q booleans have no null, sowhere not flagalso matches rows whose flag was NULL. - Out-of-range timestamps are infinities. q timestamps read from DuckDB run from 1707 to 2262. A later one, such
as the
9999-12-31that marks a current row, reads as0Wp, an earlier one as-0Wp, soselect from inst where valid_to>.z.pfinds the current rows andmax valid_tois0Wp. The order is kept, so a filter DuckDB runs keeps exactly the rows q would. q's timestamp infinities are not IEEE infinities: on such a rowvalid_to-valid_fromis a huge, meaningless timespan, not an infinity, so check a table with.duckdb.inspectbefore doing arithmetic on its timestamps. A comparison with0Wp, or with a timestamp past 2262, is run by q. - Out-of-range dates raise an error. Only DuckDB's very earliest dates are past what a q date holds. A select
that reads one fails with
'duckdb(.duckdb.err[]names the column); a select that does not read that column answers. - Time zones are dropped. TIMESTAMP WITH TIME ZONE reads as its UTC instant, whatever the DuckDB session's
TimeZonesetting is.
Columns
- Hidden columns are silent. A HUGEINT or STRUCT column simply is not there. Check
.duckdb.hiddenor.parquet.hiddenwhen a column you expected is missing. A table whose every column is hidden reads as a table with no columns. DuckDB itself writes a HUGEINT to parquet as a DOUBLE, so in a file it reads as a float. - Hive partition columns come last in
colsandmeta, after the file's own columns, and DuckDB guesses their type from the directory names (date=2024-01-02is a DATE,region=EUa VARCHAR). - A column named
icannot be written to DuckDB:iis q's row index. - A parquet source's columns are read once per session. After another program rewrites a file with new or
retyped columns, run
.parquet.refresh `:t.parquet(or.parquet.refresh[]for every source), as you would\lafter changing a kdb database. New files in a glob appear by themselves, and a file you write with.parquet.write,setorsaveis read afresh.
Queries
countof a handle is 1.count `:pq:duckdb:main:t/counts the symbol. Usecount select from `:pq:duckdb:main:t/or bind it to an external table first.- Order-dependent answers can change.
first,last,i,deltasandselect[n]depend on row order, which a foreign table does not promise. Sort or group on a real column when the order matters. - Filter on columns DuckDB can use first. Equality,
inandwithinon dates, timestamps, symbols/strings and integers run inside DuckDB and let it skip whole files and row groups. A float comparison (px>100) narrows the rows in DuckDB and is finished by q, because q compares floats with a tolerance;px within 1 2is run by q. likepatterns. Plain characters with a leading and/or trailing*run in DuckDB. Any other pattern (?,[..], a*in the middle) is narrowed in DuckDB by its literal prefix and finished by q.- Grouping by an expression (
by a mod 2) is run by q on the two columns DuckDB returns, so it reads every row; grouping by a column runs in DuckDB. - The string leniency covers symbols in comparisons, nothing else.
=,<>,<,>,<=,>=,in,withinandlikeaccept a symbol on a string column: a literal, a variable holding one, or (in awhere) an expression that reads no column. A string literal is never reinterpreted:sym="AB"is q's character-wise compare, an error or a list per row exactly as on the in-memory table.updateanddeletehave no leniency. On a q table,sym=`Aagainst a string column is a'typeerror, as in kdb. - A value is computed up front only as a
whereoperand. Inwhere qty>cfg`lim,where sym in key dorwhere sym in exec sym from refthe part that reads no column is evaluated once, where the select is written (so a function's locals count), and DuckDB is handed its value. The same kind of expression in abyor in the select phrase (select big:px>2*cfg`lim from t) is left to q: the answer is the same, but that select may run in q on the columns DuckDB returns instead of inside DuckDB. Assign the value to a variable first when you want it pushed. .duckdb.maxrowsguards only q tables stored in DuckDB. A foreign table or a parquet file is never refused for its size, so a select with no filter DuckDB can run reads every row it names.- See what ran.
.duckdb.sqlloglists every statement sent to DuckDB, and.duckdb.lastpushthe translation of the last select (::when nothing moved into DuckDB, so q did the work). - Session settings change answers.
SET default_collation='nocase'on the DuckDB connection makes some pushed text comparisons and groupings ignore case where q does not. Leave the collation alone.
SQL and writing
- SQL answers keep DuckDB's own view.
.duckdb.execands)lines can show extra columns such asqty_q_notnullorname_q_isnull, which mark exactly where a NULL and a q null differ. qSQL never shows them. - A DECIMAL in a SQL answer is its unscaled integer.
SELECT price FROM ton a DECIMAL(10,2) column answers10037for 100.37, andsum(price*size)comes back 100 times too large. qSQL reads the same column as the float 100.37. In SQL, cast it yourself:SELECT CAST(price AS DOUBLE) AS price FROM t..duckdb.getxanswers the unscaled values together with the schema that holds their scale, which is how the exact round trip works. - Keyed tables.
.parquet.writerefuses a keyed table with'type; write0!t. Remember aselect … byresult is keyed, so0!it before writing.upsertinto a keyed table stored in DuckDB does not replace rows by key: a keyed table q stored gains duplicate keys, and a table with a DuckDB PRIMARY KEY refuses the upsert. - An empty table with a general-list column (
0#([] s:("ab";"cd"))) cannot be written, because it has no type. q has no empty string column to give it one, so create the table with SQL (CREATE TABLE t (s VARCHAR)) instead. - A parquet file PeachQ wrote and another tool rewrote keeps the
q_schemaentry that says how to read it. PeachQ uses it for column types only, never trusts its values, and reads a column the entry does not describe, or an entry it cannot understand, as it would read a foreign file.
See also Storing tables in DuckDB, Parquet and the hive-partitioned parquet recipe.