pg-brainfuck

Extends PostgreSQL with Brainfuck.

  • Provides the brainfuck(input, program) function.

  • Provides a plbrainfuck procedural language to write Brainfuck functions in SQL.

  • Provides the brainfuck_fdw foreign data wrapper (FDW) to query a Brainfuck program’s output as a table, one row per line.

Install

Build and install the extension.

make
sudo make install

Then, create the extension in your database.

CREATE EXTENSION brainfuck;

Usage

Function

Execute an ad-hoc Brainfuck program.

-- https://en.wikipedia.org/wiki/Brainfuck#Hello_World%21
SELECT brainfuck('', $$
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
$$); -- E'Hello World!\n'

Language

Define your own SQL functions in Brainfuck.

-- https://www.hevanet.com/cristofd/brainfuck/rot13.b
CREATE FUNCTION rot13(text)
RETURNS text
AS $$
BEGIN
,
[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-
[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-
[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-
[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-
[>++++++++++++++<-
[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-
[>>+++++[<----->-]<<-
[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-
[>++++++++++++++<-
[>+<-[>+<-[>+<-[>+<-[>+<-
[>++++++++++++++<-
[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-
[>>+++++[<----->-]<<-
[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-
[>++++++++++++++<-
[>+<-]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]>.[-]<,]
END;
$$ LANGUAGE plbrainfuck;

Now you can use the rot13 function.

SELECT rot13('Hello'); -- 'Uryyb'

Foreign Data Wrapper

Create a new server with the brainfuck_fdw FDW.

CREATE SERVER brainfuck
FOREIGN DATA WRAPPER brainfuck_fdw;

Create a Brainfuck table, to map a Brainfuck program to line-by-line output to a PostgreSQL table.

-- Prints the Fibonacci numbers from 0, one per line, forever.
-- https://www.hevanet.com/cristofd/brainfuck/fib.b
CREATE FOREIGN TABLE fib (line text) SERVER brainfuck OPTIONS (program $$
>++++++++++>+>+[
    [+++++[>++++++++<-]>.<++++++[>--------<-]+<<<]>.>>[
        [-]<[>+<-]>>[<<+>+>-]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-
            [>+<-[>+<-[>+<-[>[-]>+>+<<<-[>+<-]]]]]]]]]]]+>>>
    ]<<<
]
$$);

Get the 4th Fibonacci number:

SELECT line FROM fib
LIMIT 1 OFFSET 3; -- '2'

Get the first number with at least 200 digits.

SELECT line FROM fib
WHERE length(line) >= 200 LIMIT 1; -- '105858027252...818468660472' (200 digits)

License

Licensed under the PostgreSQL License.