mo-sql-parsing


Namemo-sql-parsing JSON
Version 10.581.24094 PyPI version JSON
download
home_pagehttps://github.com/klahnakoski/mo-sql-parsing
SummaryMore SQL Parsing! Parse SQL into JSON parse tree
upload_time2024-04-03 00:17:24
maintainerNone
docs_urlNone
authorKyle Lahnakoski
requires_pythonNone
licenseMPL 2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # More SQL Parsing!

[![PyPI Latest Release](https://img.shields.io/pypi/v/mo-sql-parsing.svg)](https://pypi.org/project/mo-sql-parsing/)
[![Build Status](https://app.travis-ci.com/klahnakoski/mo-sql-parsing.svg?branch=master)](https://travis-ci.com/github/klahnakoski/mo-sql-parsing)
[![Downloads](https://pepy.tech/badge/mo-sql-parsing/month)](https://pepy.tech/project/mo-sql-parsing)


Parse SQL into JSON so we can translate it for other datastores!

[See changes](https://github.com/klahnakoski/mo-sql-parsing#version-changes-features)

## Objective

The objective is to convert SQL queries to JSON-izable parse trees. This originally targeted MySQL, but has grown to include other database engines. *Please [paste some SQL into a new issue](https://github.com/klahnakoski/mo-sql-parsing/issues) if it does not work for you*


## Project Status

December 2023 -  I continue to resolve issues as they are raised. There are [over 1100 tests](https://app.travis-ci.com/github/klahnakoski/mo-sql-parsing), that cover most SQL for most databases, with limited DML and UDF support, including:

  * inner queries, 
  * with clauses, 
  * window functions
  * create/drop/alter tables and views
  * insert/update/delete statements
  * create procedure and function statements (MySQL only)


## Install

    pip install mo-sql-parsing

## Parsing SQL

    >>> from mo_sql_parsing import parse
    >>> parse("select count(1) from jobs")
    {'select': {'value': {'count': 1}}, 'from': 'jobs'}
    
Each SQL query is parsed to an object: Each clause is assigned to an object property of the same name. 

    >>> parse("select a as hello, b as world from jobs")
    {'select': [{'value': 'a', 'name': 'hello'}, {'value': 'b', 'name': 'world'}], 'from': 'jobs'}

The `SELECT` clause is an array of objects containing `name` and `value` properties. 


### SQL Flavours 

There are a few parsing modes you may be interested in:

#### Double-quotes for literal strings

MySQL uses both double quotes and single quotes to declare literal strings.  This is not ansi behaviour, but it is more forgiving for programmers coming from other languages. A specific parse function is provided: 

    result = parse_mysql(sql)

#### SQLServer Identifiers (`[]`)

SQLServer uses square brackets to delimit identifiers. For example

    SELECT [Timestamp] FROM [table]
    
which conflicts with BigQuery array constructor (eg `[1, 2, 3, 4]`). You may use the SqlServer flavour with 
    
    from mo_sql_parsing import parse_sqlserver as parse

#### NULL is None

The default output for this parser is to emit a null function `{"null":{}}` wherever `NULL` is encountered in the SQL.  If you would like something different, you can replace nulls with `None` (or anything else for that matter):

    result = parse(sql, null=None)
    
this has been implemented with a post-parse rewriting of the parse tree.


#### Normalized function call form

The default behaviour of the parser is to output function calls in `simple_op` format: The operator being a key in the object; `{op: params}`.  This form can be difficult to work with because the object must be scanned for known operators, or possible optional arguments, or at least distinguished from a query object.

You can have the parser emit function calls in `normal_op` format

    >>> from mo_sql_parsing import parse, normal_op
    >>> parse("select trim(' ' from b+c)", calls=normal_op)
    
which produces calls in a normalized format

    {"op": op, "args": args, "kwargs": kwargs}

here is the pretty-printed JSON from the example above:

```
{'select': {'value': {
    'op': 'trim', 
    'args': [{'op': 'add', 'args': ['b', 'c']}], 
    'kwargs': {'characters': {'literal': ' '}}
}}}
```


## Generating SQL

You may also generate SQL from a given JSON document. This is done by the formatter, which is usually lagging the parser (Dec2023).

    >>> from mo_sql_parsing import format
    >>> format({"from":"test", "select":["a.b", "c"]})
    'SELECT a.b, c FROM test'

## Contributing

In the event that the parser is not working for you, you can help make this better but simply pasting your sql (or JSON) into a new issue. Extra points if you describe the problem. Even more points if you submit a PR with a test.  If you also submit a fix, then you also have my gratitude. 


### Run Tests

See [the tests directory](https://github.com/klahnakoski/mo-sql-parsing/tree/dev/tests) for instructions running tests, or writing new ones.

## More about implementation

SQL queries are translated to JSON objects: Each clause is assigned to an object property of the same name.

    
    # SELECT * FROM dual WHERE a>b ORDER BY a+b
    {
        "select": {"all_columns": {}} 
        "from": "dual", 
        "where": {"gt": ["a", "b"]}, 
        "orderby": {"value": {"add": ["a", "b"]}}
    }
        
Expressions are also objects, but with only one property: The name of the operation, and the value holding (an array of) parameters for that operation. 

    {op: parameters}

and you can see this pattern in the previous example:

    {"gt": ["a","b"]}
    
## Array Programming

The `mo-sql-parsing.scrub()` method is used liberally throughout the code, and it "simplifies" the JSON.  You may find this form a bit tedious to work with because the JSON property values can be values, lists of values, or missing.  Please consider converting everything to arrays: 


```
def listwrap(value):
    if value is None:
        return []
    elif isinstance(value, list)
        return value
    else:
        return [value]
```  

then you may avoid all the is-it-a-list checks :

```
for select in listwrap(parsed_result.get('select')):
    do_something(select)
```

## Version Changes, Features


### Version 10

*December 2023*

`SELECT *` now emits an `all_columns` call instead of plain star (`*`).  

```
>>> from mo_sql_parsing import parse
>>> parse("SELECT * FROM table")
{'select': {'all_columns': {}}, 'from': 'table'}
```

This works better with the `except` clause, and is more explicit when selecting all child properties.

``` 
>>> parse("SELECT a.* EXCEPT b FROM table")
>>> {"select": {"all_columns": "a", "except": "b"}, "from": "table"}
```

You may get the original behaviour by staying with version 9, or by using `all_columns="*"`:

```
>>> parse("SELECT * FROM table", all_columns="*")
{'select': "*", 'from': 'table'}
```


### Version 9

*November 2022*

Output for `COUNT(DISTINCT x)` has changed from function composition

    {"count": {"distinct": x}}

to named parameters

    {"count": x, "distinct": true}
     
This was part of a bug fix [issue142](https://github.com/klahnakoski/mo-sql-parsing/issues/142) - realizing `distinct` is just one parameter of many in an aggregate function. Specifically, using the `calls=normal_op` for clarity:
    
    >>> from mo_sql_parsing import parse, normal_op
    >>> parse("select count(distinct x)", calls=normal_op)
    
    {'select': {'value': {
        'op': 'count', 
        'args': [x], 
        'kwargs': {'distinct': True}
    }}}

### Version 8.200+

*September 2022*

* Added `ALTER TABLE` and `COPY` command parsing for Snowflake 


### Version 8
 
*November 2021*

* Prefer BigQuery `[]` (create array) over SQLServer `[]` (identity) 
* Added basic DML (`INSERT`/`UPDATE`/`DELETE`)              
* flatter `CREATE TABLE` structures. The `option` list in column definition has been flattened:<br>
    **Old column format**
    
        {"create table": {
            "columns": {
                "name": "name",
                "type": {"decimal": [2, 3]},
                "option": [
                    "not null",
                    "check": {"lt": [{"length": "name"}, 10]}
                ]
            }
        }}
        
    **New column format**
                
        {"create table": {
            "columns": {
                "name": "name", 
                "type": {"decimal": [2, 3]}
                "nullable": False,
                "check": {"lt": [{"length": "name"}, 10]} 
            }
        }}

### Version 7 

*October 2021*

* changed error reporting; still terrible
* upgraded mo-parsing library which forced version change

### Version 6 

*October 2021*

* fixed `SELECT DISTINCT` parsing
* added `DISTINCT ON` parsing

### Version 5 

*August 2021*

* remove inline module `mo-parsing`
* support `CREATE TABLE`, add SQL "flavours" emit `{null:{}}` for None

### Version 4

*November 2021*

* changed parse result of `SELECT DISTINCT`
* simpler `ORDER BY` clause in window functions

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/klahnakoski/mo-sql-parsing",
    "name": "mo-sql-parsing",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": null,
    "author": "Kyle Lahnakoski",
    "author_email": "kyle@lahnakoski.com",
    "download_url": "https://files.pythonhosted.org/packages/3d/66/cc8fcffcb7bcd20be28129e1fb4b7657e037bf10d677d5fd2fd3000fea6b/mo-sql-parsing-10.581.24094.tar.gz",
    "platform": null,
    "description": "# More SQL Parsing!\r\n\r\n[![PyPI Latest Release](https://img.shields.io/pypi/v/mo-sql-parsing.svg)](https://pypi.org/project/mo-sql-parsing/)\r\n[![Build Status](https://app.travis-ci.com/klahnakoski/mo-sql-parsing.svg?branch=master)](https://travis-ci.com/github/klahnakoski/mo-sql-parsing)\r\n[![Downloads](https://pepy.tech/badge/mo-sql-parsing/month)](https://pepy.tech/project/mo-sql-parsing)\r\n\r\n\r\nParse SQL into JSON so we can translate it for other datastores!\r\n\r\n[See changes](https://github.com/klahnakoski/mo-sql-parsing#version-changes-features)\r\n\r\n## Objective\r\n\r\nThe objective is to convert SQL queries to JSON-izable parse trees. This originally targeted MySQL, but has grown to include other database engines. *Please [paste some SQL into a new issue](https://github.com/klahnakoski/mo-sql-parsing/issues) if it does not work for you*\r\n\r\n\r\n## Project Status\r\n\r\nDecember 2023 -  I continue to resolve issues as they are raised. There are [over 1100 tests](https://app.travis-ci.com/github/klahnakoski/mo-sql-parsing), that cover most SQL for most databases, with limited DML and UDF support, including:\r\n\r\n  * inner queries, \r\n  * with clauses, \r\n  * window functions\r\n  * create/drop/alter tables and views\r\n  * insert/update/delete statements\r\n  * create procedure and function statements (MySQL only)\r\n\r\n\r\n## Install\r\n\r\n    pip install mo-sql-parsing\r\n\r\n## Parsing SQL\r\n\r\n    >>> from mo_sql_parsing import parse\r\n    >>> parse(\"select count(1) from jobs\")\r\n    {'select': {'value': {'count': 1}}, 'from': 'jobs'}\r\n    \r\nEach SQL query is parsed to an object: Each clause is assigned to an object property of the same name. \r\n\r\n    >>> parse(\"select a as hello, b as world from jobs\")\r\n    {'select': [{'value': 'a', 'name': 'hello'}, {'value': 'b', 'name': 'world'}], 'from': 'jobs'}\r\n\r\nThe `SELECT` clause is an array of objects containing `name` and `value` properties. \r\n\r\n\r\n### SQL Flavours \r\n\r\nThere are a few parsing modes you may be interested in:\r\n\r\n#### Double-quotes for literal strings\r\n\r\nMySQL uses both double quotes and single quotes to declare literal strings.  This is not ansi behaviour, but it is more forgiving for programmers coming from other languages. A specific parse function is provided: \r\n\r\n    result = parse_mysql(sql)\r\n\r\n#### SQLServer Identifiers (`[]`)\r\n\r\nSQLServer uses square brackets to delimit identifiers. For example\r\n\r\n    SELECT [Timestamp] FROM [table]\r\n    \r\nwhich conflicts with BigQuery array constructor (eg `[1, 2, 3, 4]`). You may use the SqlServer flavour with \r\n    \r\n    from mo_sql_parsing import parse_sqlserver as parse\r\n\r\n#### NULL is None\r\n\r\nThe default output for this parser is to emit a null function `{\"null\":{}}` wherever `NULL` is encountered in the SQL.  If you would like something different, you can replace nulls with `None` (or anything else for that matter):\r\n\r\n    result = parse(sql, null=None)\r\n    \r\nthis has been implemented with a post-parse rewriting of the parse tree.\r\n\r\n\r\n#### Normalized function call form\r\n\r\nThe default behaviour of the parser is to output function calls in `simple_op` format: The operator being a key in the object; `{op: params}`.  This form can be difficult to work with because the object must be scanned for known operators, or possible optional arguments, or at least distinguished from a query object.\r\n\r\nYou can have the parser emit function calls in `normal_op` format\r\n\r\n    >>> from mo_sql_parsing import parse, normal_op\r\n    >>> parse(\"select trim(' ' from b+c)\", calls=normal_op)\r\n    \r\nwhich produces calls in a normalized format\r\n\r\n    {\"op\": op, \"args\": args, \"kwargs\": kwargs}\r\n\r\nhere is the pretty-printed JSON from the example above:\r\n\r\n```\r\n{'select': {'value': {\r\n    'op': 'trim', \r\n    'args': [{'op': 'add', 'args': ['b', 'c']}], \r\n    'kwargs': {'characters': {'literal': ' '}}\r\n}}}\r\n```\r\n\r\n\r\n## Generating SQL\r\n\r\nYou may also generate SQL from a given JSON document. This is done by the formatter, which is usually lagging the parser (Dec2023).\r\n\r\n    >>> from mo_sql_parsing import format\r\n    >>> format({\"from\":\"test\", \"select\":[\"a.b\", \"c\"]})\r\n    'SELECT a.b, c FROM test'\r\n\r\n## Contributing\r\n\r\nIn the event that the parser is not working for you, you can help make this better but simply pasting your sql (or JSON) into a new issue. Extra points if you describe the problem. Even more points if you submit a PR with a test.  If you also submit a fix, then you also have my gratitude. \r\n\r\n\r\n### Run Tests\r\n\r\nSee [the tests directory](https://github.com/klahnakoski/mo-sql-parsing/tree/dev/tests) for instructions running tests, or writing new ones.\r\n\r\n## More about implementation\r\n\r\nSQL queries are translated to JSON objects: Each clause is assigned to an object property of the same name.\r\n\r\n    \r\n    # SELECT * FROM dual WHERE a>b ORDER BY a+b\r\n    {\r\n        \"select\": {\"all_columns\": {}} \r\n        \"from\": \"dual\", \r\n        \"where\": {\"gt\": [\"a\", \"b\"]}, \r\n        \"orderby\": {\"value\": {\"add\": [\"a\", \"b\"]}}\r\n    }\r\n        \r\nExpressions are also objects, but with only one property: The name of the operation, and the value holding (an array of) parameters for that operation. \r\n\r\n    {op: parameters}\r\n\r\nand you can see this pattern in the previous example:\r\n\r\n    {\"gt\": [\"a\",\"b\"]}\r\n    \r\n## Array Programming\r\n\r\nThe `mo-sql-parsing.scrub()` method is used liberally throughout the code, and it \"simplifies\" the JSON.  You may find this form a bit tedious to work with because the JSON property values can be values, lists of values, or missing.  Please consider converting everything to arrays: \r\n\r\n\r\n```\r\ndef listwrap(value):\r\n    if value is None:\r\n        return []\r\n    elif isinstance(value, list)\r\n        return value\r\n    else:\r\n        return [value]\r\n```  \r\n\r\nthen you may avoid all the is-it-a-list checks :\r\n\r\n```\r\nfor select in listwrap(parsed_result.get('select')):\r\n    do_something(select)\r\n```\r\n\r\n## Version Changes, Features\r\n\r\n\r\n### Version 10\r\n\r\n*December 2023*\r\n\r\n`SELECT *` now emits an `all_columns` call instead of plain star (`*`).  \r\n\r\n```\r\n>>> from mo_sql_parsing import parse\r\n>>> parse(\"SELECT * FROM table\")\r\n{'select': {'all_columns': {}}, 'from': 'table'}\r\n```\r\n\r\nThis works better with the `except` clause, and is more explicit when selecting all child properties.\r\n\r\n``` \r\n>>> parse(\"SELECT a.* EXCEPT b FROM table\")\r\n>>> {\"select\": {\"all_columns\": \"a\", \"except\": \"b\"}, \"from\": \"table\"}\r\n```\r\n\r\nYou may get the original behaviour by staying with version 9, or by using `all_columns=\"*\"`:\r\n\r\n```\r\n>>> parse(\"SELECT * FROM table\", all_columns=\"*\")\r\n{'select': \"*\", 'from': 'table'}\r\n```\r\n\r\n\r\n### Version 9\r\n\r\n*November 2022*\r\n\r\nOutput for `COUNT(DISTINCT x)` has changed from function composition\r\n\r\n    {\"count\": {\"distinct\": x}}\r\n\r\nto named parameters\r\n\r\n    {\"count\": x, \"distinct\": true}\r\n     \r\nThis was part of a bug fix [issue142](https://github.com/klahnakoski/mo-sql-parsing/issues/142) - realizing `distinct` is just one parameter of many in an aggregate function. Specifically, using the `calls=normal_op` for clarity:\r\n    \r\n    >>> from mo_sql_parsing import parse, normal_op\r\n    >>> parse(\"select count(distinct x)\", calls=normal_op)\r\n    \r\n    {'select': {'value': {\r\n        'op': 'count', \r\n        'args': [x], \r\n        'kwargs': {'distinct': True}\r\n    }}}\r\n\r\n### Version 8.200+\r\n\r\n*September 2022*\r\n\r\n* Added `ALTER TABLE` and `COPY` command parsing for Snowflake \r\n\r\n\r\n### Version 8\r\n \r\n*November 2021*\r\n\r\n* Prefer BigQuery `[]` (create array) over SQLServer `[]` (identity) \r\n* Added basic DML (`INSERT`/`UPDATE`/`DELETE`)              \r\n* flatter `CREATE TABLE` structures. The `option` list in column definition has been flattened:<br>\r\n    **Old column format**\r\n    \r\n        {\"create table\": {\r\n            \"columns\": {\r\n                \"name\": \"name\",\r\n                \"type\": {\"decimal\": [2, 3]},\r\n                \"option\": [\r\n                    \"not null\",\r\n                    \"check\": {\"lt\": [{\"length\": \"name\"}, 10]}\r\n                ]\r\n            }\r\n        }}\r\n        \r\n    **New column format**\r\n                \r\n        {\"create table\": {\r\n            \"columns\": {\r\n                \"name\": \"name\", \r\n                \"type\": {\"decimal\": [2, 3]}\r\n                \"nullable\": False,\r\n                \"check\": {\"lt\": [{\"length\": \"name\"}, 10]} \r\n            }\r\n        }}\r\n\r\n### Version 7 \r\n\r\n*October 2021*\r\n\r\n* changed error reporting; still terrible\r\n* upgraded mo-parsing library which forced version change\r\n\r\n### Version 6 \r\n\r\n*October 2021*\r\n\r\n* fixed `SELECT DISTINCT` parsing\r\n* added `DISTINCT ON` parsing\r\n\r\n### Version 5 \r\n\r\n*August 2021*\r\n\r\n* remove inline module `mo-parsing`\r\n* support `CREATE TABLE`, add SQL \"flavours\" emit `{null:{}}` for None\r\n\r\n### Version 4\r\n\r\n*November 2021*\r\n\r\n* changed parse result of `SELECT DISTINCT`\r\n* simpler `ORDER BY` clause in window functions\r\n",
    "bugtrack_url": null,
    "license": "MPL 2.0",
    "summary": "More SQL Parsing! Parse SQL into JSON parse tree",
    "version": "10.581.24094",
    "project_urls": {
        "Homepage": "https://github.com/klahnakoski/mo-sql-parsing"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f29b63e0b7159a2dc9d280c5e4b79bdd20b519ebbbe02a8cce17cf78ce41a2d4",
                "md5": "0c21408d8f85bfc3de35f18632108039",
                "sha256": "0a7e4353641aaaf1b88159981cfae3791d8ba94082b047661cbd35ed38d5672f"
            },
            "downloads": -1,
            "filename": "mo_sql_parsing-10.581.24094-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "0c21408d8f85bfc3de35f18632108039",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 42732,
            "upload_time": "2024-04-03T00:17:21",
            "upload_time_iso_8601": "2024-04-03T00:17:21.749974Z",
            "url": "https://files.pythonhosted.org/packages/f2/9b/63e0b7159a2dc9d280c5e4b79bdd20b519ebbbe02a8cce17cf78ce41a2d4/mo_sql_parsing-10.581.24094-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3d66cc8fcffcb7bcd20be28129e1fb4b7657e037bf10d677d5fd2fd3000fea6b",
                "md5": "cbeb6433e73a04967eb31c78e193beb4",
                "sha256": "391c639cf009cb25998699fdbcebadc796b750ec313db99cc38ae4d5e7009fd9"
            },
            "downloads": -1,
            "filename": "mo-sql-parsing-10.581.24094.tar.gz",
            "has_sig": false,
            "md5_digest": "cbeb6433e73a04967eb31c78e193beb4",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 44343,
            "upload_time": "2024-04-03T00:17:24",
            "upload_time_iso_8601": "2024-04-03T00:17:24.675847Z",
            "url": "https://files.pythonhosted.org/packages/3d/66/cc8fcffcb7bcd20be28129e1fb4b7657e037bf10d677d5fd2fd3000fea6b/mo-sql-parsing-10.581.24094.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-03 00:17:24",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "klahnakoski",
    "github_project": "mo-sql-parsing",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "mo-sql-parsing"
}
        
Elapsed time: 0.23444s