Giter VIP home page Giter VIP logo

pgjq's Introduction

pgJQ: Use jq in Postgres

Docker Pulls GitHub Repo stars

Note: If you like this idea check out: liteJQ: jq extension for SQLite

The pgJQ extension embeds the standard jq compiler and brings the much loved jq lang to Postgres.

It adds a jqprog data type to express jq programs and a jq(jsonb, jqprog) function to execute them on jsonb objects. It works seamlessly with standard jsonb functions, operators, and jsonpath.

SELECT jq('[{"bar": "baz", "balance": 7.77, "active":false}]'::jsonb, '.[0].bar');
  jq   
-------
 "baz"
(1 row)

til

Usage

Filters

You can run basic filters:

SELECT jq('[{"bar": "baz", "balance": 7.77, "active":false}]'::jsonb, '.[0].bar');
  jq   
-------
 "baz"
(1 row)

jsonb @@ jqprog

If you're a syntactic sugar addict, you can use the @@ operator to achieve the same. It's better be explicit with the ::jqprog when using operators.

SELECT '[{"bar": "baz", "balance": 7.77, "active":false}]' @@ '.[0].bar'::jqprog;
  jq   
-------
 "baz"
(1 row)

Complex Programs

You can run more complex jq programs too:

SELECT jq('[true,false,[5,true,[true,[false]],false]]',
          '(..|select(type=="boolean")) |= if . then 1 else 0 end');
             jq              
-----------------------------
 [1, 0, [5, 1, [1, [0]], 0]]
(1 row)
SELECT jq('[1,5,3,0,7]' , '(.[] | select(. >= 2)) |= empty');
   jq   
--------
 [1, 0]
(1 row)

Passing Arguments to jqprog

If you want to pass dynamic arguments to jqprog, you can pass them as a jsonb object and refer to them as $var.

select jq('{
  "runner": 1,
  "message": "jobStatus",
  "jobs": [
    {
      "id": 9,
      "is_successfull": true
    },
    {
      "id": 100,
      "is_successfull": false,
      "metdata": {
        "environ": "prod"
      }
    }
  ]
}'::jsonb, '.jobs[] | select(.is_successfull == $is_success and .id == 100) | .', '{"is_success": false, "id": 100}');
                                  jq                                  
----------------------------------------------------------------------
 {"id": 100, "metdata": {"environ": "prod"}, "is_successfull": false}
(1 row)

jq and jsonpath

You can even chain jq and jsonpath together!

Note here that the later part - '{trans}' @> '{"cust": "baz"}' is jsonpath, not jq code.

SELECT jq('[
  {
    "cust": "baz",
    "trans": {
      "balance": 100,
      "date": "2023-08-01"
    },
    "active": true,
    "geo": {
      "branch": "paloukia"
    }
  }
]', '(.[] | select(.active == true))') - '{trans}' @> '{"cust": "baz"}';
 ?column? 
----------
 t
(1 row)

If you opt for using operators here, you should help the parser by adding parentheses and explicit casts.

SELECT ('[
  {
    "cust": "baz",
    "trans": {
      "balance": 100,
      "date": "2023-08-01"
    },
    "active": true,
    "geo": {
      "branch": "paloukia"
    }
  }
]' @@ '(.[] | select(.active == true))'::jqprog) - '{trans}' @> '{"cust": "baz"}';

It is strongly recommended to be explicit with type casts and ordering when using overloaded operators, especially when you're working a lot with text. Otherwise, you'll find yourself in an obfuscated labyrinth of jqprogs, jsonbs, jsonpaths and possibly tsvectors , impossible to escape from.

Working with Files

If you have superuser privileges in Postgres you can use the pg_read_file to run your queries on JSON files.

SELECT jq(pg_read_file('/path/to/f.json', '.[]'))

You can see more examples in the test cases or try reproducing the jq manual .

Installation

git clone https://github.com/Florents-Tselai/pgJQ.git
cd pgJQ
make install # set PG_CONFIG=/path/to/bin/pg_config if necessary.
make installcheck

In a Postgres session run

CREATE EXTENSION pgjq

How it Works

pgJQ does not re-implement the jq lang in Postgres. It instead embeds the standard jq compiler and uses it to parse jq programs supplied in SQL queries. These programs are fed with jsonb objects as input.

Issues

jq has evolved from just a cli tool to a full-fledged DSL, but it still remains a 20-80 tool.

pgJQ has been TDDed against those 20% of the cases. If you come across regressions between vanilla jq and pgJQ, especially around piped filters or complex functions, please do add an issue, along with a test case!

Keeping in mind, though, that there's probably not much point reproducing the whole DSL in an RDBMS context.

Some known issues are:

  • Only string, bool and numeric arguments can be passed to jqprog.
  • Currently, jq programs including pipes, like .[] | .name are buggy and unpredictable.
  • Modules are not supported, but they could be theoretically supported, given that Postgres is fairly open to dynamic loading.

pgjq's People

Contributors

florents-tselai avatar timwmillard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

pgjq's Issues

Eliminate the `jq` modicifaction

After working on liteJQ, I realized that I invented the universe, the wheel and an awkward version of jqlib.

Now that I learned to work with jqlib I should try to greatly simplify pgjq.c

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.