PHPackages                             thomas-0816/pdo-duckdb-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. thomas-0816/pdo-duckdb-php

ActivePhp-ext[Database &amp; ORM](/categories/database)

thomas-0816/pdo-duckdb-php
==========================

PHP PDO DuckDB

1.5.5.1(2w ago)61.9k1MITPHPPHP &gt;=8.2CI passing

Since Jun 28Pushed 2w agoCompare

[ Source](https://github.com/thomas-0816/pdo-duckdb-php)[ Packagist](https://packagist.org/packages/thomas-0816/pdo-duckdb-php)[ RSS](/packages/thomas-0816-pdo-duckdb-php/feed)WikiDiscussions main Synced 2w ago

READMEChangelog (10)DependenciesVersions (27)Used By (0)

PHP PDO DuckDB
==============

[](#php-pdo-duckdb)

[![logo](logo.jpg?3)](logo.jpg?3)

DuckDB is an embedded SQL database designed for high-performance analytics (OLAP).

`pdo_duckdb` is a native DuckDB database driver for the PHP Data Objects (PDO) interface.
As a native PHP extension, it is implemented in C/C++ and does not require PHP FFI or preloading.
It is also thread safe and fully tested with FrankenPHP (PHP-ZTS).
The release packages contain pre-compiled binaries for all supported platforms and DuckDB is directly included.
DuckDB extensions work the same way as they do in DuckDB CLI.

This extension supports all DuckDB types: Text, Numeric, Date, Time, Interval, JSON, Array, Struct, Map, List, Enum, Variant, Geometry, Union, Bitstring, Blob and Boolean.

Supported PHP versions (nts &amp; zts): 8.2 8.3 8.4 8.5

Supported operating systems: Ubuntu 24.04/26.04, Debian 12/13, Fedora 42/43, AmazonLinux, openSUSE 16, Wolfi OS, Windows Server 2022/2025 (x64), macOS 14-26 (arm64)

Supported SAPIs: php-cli, php-fpm, FrankenPHP, mod\_php

Install and setup with 🥧 [PIE](https://github.com/php/pie)
----------------------------------------------------------

[](#install-and-setup-with--pie)

```
pie install thomas-0816/pdo-duckdb-php
```

Install and setup with 🧟 [FrankenPHP](https://frankenphp.dev/) (Debian/Ubuntu)
------------------------------------------------------------------------------

[](#install-and-setup-with--frankenphp-debianubuntu)

```
    sudo curl -s https://pkg.henderkes.com/api/packages/85/debian/repository.key -o /etc/apt/keyrings/static-php85.asc
    echo "deb [signed-by=/etc/apt/keyrings/static-php85.asc] https://pkg.henderkes.com/api/packages/85/debian php-zts main" | \
        sudo tee -a /etc/apt/sources.list.d/static-php85.list
    sudo apt-get update
    sudo apt-get install php-zts-cli php-zts-pdo frankenphp pie-zts
    sudo pie-zts install thomas-0816/pdo-duckdb-php

    # test
    frankenphp php-cli -r 'print_r((new PDO("duckdb::memory:"))->query("SELECT 42 as n")->fetch(PDO::FETCH_ASSOC));'
```

Install and setup with Docker
-----------------------------

[](#install-and-setup-with-docker)

```
    FROM php:8.5-cli
    RUN exec("CREATE TABLE table1 (id INTEGER, amount DECIMAL(10, 2), description VARCHAR)");

$statement = $duckDb->prepare("INSERT INTO table1 VALUES (?, ?, ?)");
$statement->execute([1, 42.21, 'Hello DuckDB! 🐘 💓 🦆']);

$statement = $duckDb->query("SELECT * FROM table1");
print_r($statement->fetchAll(PDO::FETCH_ASSOC));

# Array
#     [0] => Array
#         [id] => 1
#         [amount] => 42.21
#         [description] => Hello DuckDB! 🐘 💓 🦆
```

Open databases from disk or in-memory
-------------------------------------

[](#open-databases-from-disk-or-in-memory)

```
$db = new PDO('duckdb::memory:'); // open in-memory database

$db = new PDO('duckdb:/tmp/test.db'); // open database file from disk

// open database file as read-only
$db = new PDO('duckdb:/tmp/test.db', null, null, [
    PDO::DUCKDB_ATTR_CONFIG => ['access_mode' => 'read_only']
]);
```

Read and write Parquet files
----------------------------

[](#read-and-write-parquet-files)

```
$db = new PDO('duckdb::memory:');
$db->exec("CREATE TABLE table1 (id INTEGER, text VARCHAR USING COMPRESSION zstd, data JSON)");

$statement = $db->prepare("INSERT INTO table1 VALUES (?, ?, ?)");
$statement->execute([1, 'Hello DuckDB 🦆', ['foo' => 'bar', 'baz' => 42]]);

$db->exec("COPY (SELECT * FROM table1) TO '/tmp/table1.parquet' (COMPRESSION zstd)");

foreach ($db->query("SELECT * FROM '/tmp/table1.parquet'", PDO::FETCH_ASSOC) as $row) {
    print_r($row);
}

# Array
#     [id] => 1
#     [text] => Hello DuckDB 🦆
#     [data] => Array
#         [foo] => bar
#         [baz] => 42
```

**Apache Parquet**: very fast and efficient column based storage file format containing one table of data.
Each column is split into several column groups. Depending on the query, the file can be read partially by certain columns groups.
Different compression or dictionary algorithms can be applied to each column. Also supports encryption.

**Note**: You can read and save Parquet files on local file systems or directly on [S3 object storage](https://duckdb.org/docs/lts/core_extensions/httpfs/s3api).

Read CSV files with SQL
-----------------------

[](#read-csv-files-with-sql)

```
$list = [
    ['aaa', 'bbb', 'ccc'],
    ['123', '456', '789'],
    ['aaa', 'bbb', 'ccc']
];
$fp = fopen('/tmp/test.csv', 'w');
foreach ($list as $fields) {
    fputcsv($fp, $fields, ',', '"', "");
}
fclose($fp);

$db = new PDO('duckdb::memory:');
$statement = $db->query("SELECT * FROM '/tmp/test.csv'");
print_r($statement->fetchAll(PDO::FETCH_ASSOC));

# Array
#     [0] => Array
#         [aaa] => 123
#         [bbb] => 456
#         [ccc] => 789
#     [1] => Array
#         [aaa] => aaa
#         [bbb] => bbb
#         [ccc] => ccc
```

Read JSON files with SQL
------------------------

[](#read-json-files-with-sql)

```
file_put_contents('/tmp/logs.json', json_encode(['log' => 'log text']) . PHP_EOL, FILE_APPEND);
file_put_contents('/tmp/logs.json', json_encode(['log' => 'log text 2']) . PHP_EOL, FILE_APPEND);

$db = new PDO('duckdb::memory:');
$statement = $db->query("SELECT * FROM '/tmp/logs.json'");
print_r($statement->fetchAll(PDO::FETCH_ASSOC));

# Array
#     [0] => Array
#         [log] => log text
#     [1] => Array
#         [log] => log text 2

$db->exec("COPY (SELECT * FROM '/tmp/logs.json') TO '/tmp/logs_json.parquet' (COMPRESSION zstd)");
```

Use structured columns with a fixed schema
------------------------------------------

[](#use-structured-columns-with-a-fixed-schema)

```
// s is array{v: string, i: int, a: string[], d: float}

$db = new PDO('duckdb::memory:');
$db->exec("CREATE TABLE table1 (s STRUCT(v VARCHAR, i INTEGER, a VARCHAR[], d DECIMAL))");

$statement = $db->prepare("INSERT INTO table1 VALUES (?)");
$statement->execute([['v' => 'foo', 'i' => 21, 'a' => ['b', 'c'], 'd' => 42.21]]);

$statement = $db->query("SELECT * FROM table1");
print_r($statement->fetch(PDO::FETCH_ASSOC));

# Array
#     [s] => Array
#         [v] => foo
#         [i] => 21
#         [a] => Array
#             [0] => b
#             [1] => c
#         [d] => 42.21
```

Cast array columns to JSON-string
---------------------------------

[](#cast-array-columns-to-json-string)

```
$db = new PDO('duckdb::memory:');
$db->exec("CREATE TABLE table1 (v VARCHAR[])");
$db->exec("INSERT INTO table1 VALUES (['a', 'b'])");

$statement = $db->query("SELECT v FROM table1");
print_r($statement->fetch(PDO::FETCH_ASSOC));

# Array
#     [v] => Array
#         [0] => a
#         [1] => b

$statement = $db->query("SELECT v::json::varchar as v FROM table1");
print_r($statement->fetch(PDO::FETCH_ASSOC));

# Array
#     [v] => ["a","b"]
```

Auto increment columns
----------------------

[](#auto-increment-columns)

```
$db = new PDO('duckdb::memory:');
$db->exec('CREATE SEQUENCE table1_id');
$db->exec("CREATE TABLE table1 (id INTEGER PRIMARY KEY DEFAULT nextval('table1_id'))");
$statement = $db->query("INSERT INTO table1 VALUES (default) RETURNING *");
print_r($statement->fetch(PDO::FETCH_ASSOC));

# Array
#     [id] => 1
```

Differences to MySQL / MariaDB
------------------------------

[](#differences-to-mysql--mariadb)

```
$db = new PDO('duckdb::memory:');
$statement = $db->query("SELECT
    0/0, 1/0, -1/0,
    nullif(0/0, 'NAN'), nullif(1/0, 'INF'), nullif(-1/0, '-INF')");
var_export($statement->fetch(PDO::FETCH_NUM));

# array (
#     0 => NAN, // MySQL,MariaDB: NULL
#     1 => INF, // MySQL,MariaDB: NULL
#     2 => -INF, // MySQL,MariaDB: NULL
#     3 => NULL,
#     4 => NULL,
#     5 => NULL,
# )
```

Copy data from MySQL or MariaDB to Parquet
------------------------------------------

[](#copy-data-from-mysql-or-mariadb-to-parquet)

Start MariaDB container, create and fill "orders" table:

```
docker run --rm -it -p 3306:3306 -e MARIADB_ROOT_PASSWORD=secret -e MARIADB_DATABASE=testdb mariadb:12
mysql -h 127.0.0.1 -u root -psecret testdb -e "
    CREATE TABLE orders (id integer primary key, customer integer, amount decimal(12, 2), origin varchar(255));
    INSERT INTO orders VALUES (1, 42, 123.42, 'shop');
    INSERT INTO orders VALUES (2, 21, 12.21, 'offline');
"
```

Use DuckDB MySQL extension to copy "orders" table from MariaDB to a parquet file:

```
$db = new PDO('duckdb::memory:');
$db->exec('INSTALL mysql');
$db->exec("ATTACH 'host=127.0.0.1 port=3306 user=root password=secret database=testdb' AS testdb (TYPE mysql)");
$db->exec("COPY (select * from testdb.orders) TO '/tmp/orders.parquet' (FORMAT parquet)");

$rows = $db->query("SELECT * from '/tmp/orders.parquet'")->fetchAll(PDO::FETCH_ASSOC);
print_r($rows);

# Array
#     [0] => Array
#         [id] => 1
#         [customerId] => 42
#         [amount] => 123.42
#         [origin] => shop
#     [1] => Array
#         [id] => 2
#         [customerId] => 21
#         [amount] => 12.21
#         [origin] => offline
```

Read public data using HTTPs, JSON and CSV
------------------------------------------

[](#read-public-data-using-https-json-and-csv)

```
$db = new PDO('duckdb::memory:');

$url = 'https://bulk.meteostat.net/v2/stations/lite.json.gz';
$rows = $db->query("select id, name.en from read_json('{$url}') WHERE name.en like '%Berlin%' limit 2");
echo json_encode($rows->fetchAll(PDO::FETCH_ASSOC)), PHP_EOL;

$url = 'https://data.meteostat.net/hourly/2026/10381.csv.gz';
$rows = $db->query("select hour, temp from read_csv('{$url}') where year = 2026 and month = 7 and day = 25 and hour > 9 limit 4");
echo json_encode($rows->fetchAll(PDO::FETCH_ASSOC)), PHP_EOL;

# [{"id":"10381","en":"Berlin \/ Dahlem"},{"id":"10382","en":"Berlin \/ Tegel"}]
# [{"hour":10,"temp":24.1},{"hour":11,"temp":25.5},{"hour":12,"temp":26.4},{"hour":13,"temp":27.4}]
```

Security
--------

[](#security)

```
    # Disable extension loading
    SET autoload_known_extensions = false;
    SET autoinstall_known_extensions = false;
    SET allow_community_extensions = false;

    # Disable external file access, directory white listing
    SET allowed_directories = ['/tmp'];
    SET enable_external_access = false;

    # Resource limits
    SET threads = 4;
    SET memory_limit = '4GB';
    SET max_temp_directory_size = '4GB';

    https://duckdb.org/docs/lts/operations_manual/securing_duckdb/overview
```

Compile NTS
-----------

[](#compile-nts)

```
    git clone --depth=1 --branch=main https://github.com/thomas-0816/pdo-duckdb.git
    cd pdo_duckdb

    wget https://github.com/duckdb/duckdb/releases/download/v1.5.5/libduckdb-src.zip
    unzip -o libduckdb-src.zip duckdb.h duckdb.hpp -d ./

    wget https://github.com/duckdb/duckdb/releases/download/v1.5.5/static-libs-linux-amd64.zip
    unzip -o static-libs-linux-amd64.zip libduckdb_static.a -d ./

    phpize
    ./configure --with-pdo-duckdb
    make
    NO_INTERACTION=1 TEST_PHP_ARGS="--show-diff --show-clean -q" make test

    sudo make install
    sudo sh -c 'echo "extension=pdo_duckdb.so" > /etc/php/8.5/mods-available/pdo_duckdb.ini'
    sudo phpenmod pdo_duckdb

    php -m | grep duckdb
    php test.php
```

Compile ZTS
-----------

[](#compile-zts)

```
    git clone --depth=1 --branch=main https://github.com/thomas-0816/pdo-duckdb.git
    cd pdo_duckdb

    wget https://github.com/duckdb/duckdb/releases/download/v1.5.5/libduckdb-src.zip
    unzip -o libduckdb-src.zip duckdb.h duckdb.hpp -d ./

    wget https://github.com/duckdb/duckdb/releases/download/v1.5.5/static-libs-linux-amd64.zip
    unzip -o static-libs-linux-amd64.zip libduckdb_static.a -d ./

    phpize-zts
    ./configure --with-pdo-duckdb --with-php-config=php-config-zts
    make
    NO_INTERACTION=1 TEST_PHP_ARGS="--show-diff --show-clean -q" make test

    sudo make install
    sudo sh -c 'echo "extension=pdo_duckdb.so" > /etc/php-zts/conf.d/pdo_duckdb.ini'

    php-zts -m | grep duckdb
    php-zts test.php
```

Why DuckDB?
-----------

[](#why-duckdb)

In-Process Architecture: Like SQLite, DuckDB embeds directly into host applications, eliminating the need for a separate server setup.

Extreme Analytical Speed: It uses columnar storage and vectorized (batch) processing, running analytics 10–100x faster than traditional row-oriented databases.

"Larger-than-Memory" Processing: DuckDB gracefully spills data to disk, allowing you to process massive datasets (e.g., 50GB+) on a machine with minimal RAM (e.g., 1GB).

File-Format Agnostic: It can query flat files (JSON, CSV, and Parquet) directly via SQL without needing to import or load the data into a database first.

No Infrastructure Cost: It brings data warehouse-level performance to your local laptop or local server.

DuckDB achieves blazing-fast analytical performance through its embedded, serverless multi-core architecture combined with columnar storage and vectorized execution. By executing queries directly within the host application, it eliminates serialization and network overhead, processing data in batches (vectors) rather than row-by-row for unparalleled speed.

[https://duckdb.org/why\_duckdb](https://duckdb.org/why_duckdb)

Key Performance Advantages:

Vectorized Query Execution: Unlike row-oriented engines, DuckDB processes data in cache-friendly batches (vectors). This allows modern hardware to operate on entire arrays of data simultaneously, drastically reducing CPU cycles per query.

Columnar Storage: Data is stored by column rather than by row. For analytical queries that only require a few metrics, DuckDB only reads the relevant columns from disk/memory, saving massive amounts of I/O.

Zero-Copy In-Process Engine: As an in-process database, DuckDB runs directly in the memory space of your application.

Advanced Query Optimizer: DuckDB features an advanced query optimizer that handles filter pushdowns, unnesting of subqueries, and dynamic runtime filters. This ensures queries only scan necessary data and avoids full-table sorting when possible.

Direct File Querying: You can query large datasets in open formats like Parquet and CSV directly on disk or in cloud storage (like AWS S3) without needing to import or convert the data first.

Development
-----------

[](#development)

```
    # sanity check to detect crashes
    php -d extension=$(pwd)/modules/pdo_duckdb.so test.php

    php run-tests.php -d extension=$(pwd)/modules/pdo_duckdb.so --show-diff --show-clean -q

    php-zts run-tests.php -d extension=$(pwd)/modules/pdo_duckdb.so --show-diff --show-clean -q

    # test PHP 8.2-8.5
    docker build --no-cache -f Dockerfile -t pdo_duckdb .
    docker run --rm -it pdo_duckdb

    make EXTRA_CFLAGS="-Wall -Wextra -Wno-unused-parameter" EXTRA_CXXFLAGS="-Wall -Wextra -Wno-unused-parameter"
```

AI Disclosure
-------------

[](#ai-disclosure)

The C code is written by AI, the tests are written without AI.

License
-------

[](#license)

MIT License

###  Health Score

51

—

FairBetter than 95% of packages

Maintenance97

Actively maintained with recent releases

Popularity29

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

25

Last Release

16d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b2d76ab33e3380db92d1488fbce154b710a4f0795eb337f46cfc2596b588d41a?d=identicon)[thomas-0816](/maintainers/thomas-0816)

---

Top Contributors

[![thomas-0816](https://avatars.githubusercontent.com/u/941223?v=4)](https://github.com/thomas-0816 "thomas-0816 (470 commits)")

### Embed Badge

![Health badge](/badges/thomas-0816-pdo-duckdb-php/health.svg)

```
[![Health](https://phpackages.com/badges/thomas-0816-pdo-duckdb-php/health.svg)](https://phpackages.com/packages/thomas-0816-pdo-duckdb-php)
```

###  Alternatives

[jdorn/sql-formatter

a PHP SQL highlighting library

3.8k117.8M121](/packages/jdorn-sql-formatter)[backup-manager/backup-manager

A framework agnostic database backup manager with user-definable procedures and support for S3, Dropbox, FTP, SFTP, and more with drivers for popular frameworks.

1.7k1.6M11](/packages/backup-manager-backup-manager)[propel/propel1

Propel is an open-source Object-Relational Mapping (ORM) for PHP5.

8351.6M88](/packages/propel-propel1)[insolita/yii2-migration-generator

Set of gii tools for generating files for migration by schema of table , phpdoc or table data

108508.0k5](/packages/insolita-yii2-migration-generator)[xpdo/xpdo

A PDO-based Object/Relational Bridge Library

7088.4k4](/packages/xpdo-xpdo)[voku/session2db

A PHP library acting as a wrapper for PHP's default session handling functions which stores data in a MySQL database, providing both better performance and better security and protection against session fixation and session hijacking.

3220.0k](/packages/voku-session2db)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
