├── .github └── workflows │ └── test.yml ├── LICENSE ├── README.md ├── docker-compose.yml ├── justfile ├── messages.pl ├── postgresql.pl ├── sql_query.pl ├── tester.lgt ├── tests.lgt └── types.pl /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: [push] 3 | 4 | jobs: 5 | test: 6 | runs-on: ubuntu-22.04 7 | services: 8 | postgres: 9 | image: postgres:16.0-alpine 10 | env: 11 | POSTGRES_USER: postgres 12 | POSTGRES_PASSWORD: postgres 13 | POSTGRES_DB: postgres 14 | POSTGRES_HOST_AUTH_METHOD: password 15 | options: >- 16 | --health-cmd pg_isready 17 | --health-interval 10s 18 | --health-timeout 5s 19 | --health-retries 5 20 | ports: 21 | - 5432:5432 22 | steps: 23 | - name: Install Rust cargo 24 | uses: actions-rs/toolchain@v1 25 | with: 26 | toolchain: stable 27 | profile: minimal 28 | components: cargo 29 | - name: Checkout 30 | uses: actions/checkout@v3 31 | - name: Checkout Scryer Prolog 32 | uses: actions/checkout@v3 33 | with: 34 | repository: mthom/scryer-prolog 35 | path: scryer-prolog 36 | - name: Compile Scryer Prolog 37 | run: cargo build --release 38 | working-directory: scryer-prolog 39 | - name: Install Scryer Prolog 40 | run: sudo cp scryer-prolog/target/release/scryer-prolog /usr/bin/scryer-prolog 41 | - name: Install Logtalk 42 | uses: logtalk-actions/setup-logtalk@master 43 | with: 44 | logtalk-version: 3.70.0 45 | - name: Execute tests 46 | run: logtalk_tester -p scryer 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # postgresql-prolog 2 | A Prolog library to connect to PostgreSQL databases 3 | 4 | # Compatible systems 5 | 6 | * [Scryer Prolog](https://github.com/mthom/scryer-prolog) 7 | 8 | # Installation 9 | 10 | The library itself are just four Prolog files (postgresql.pl, sql_query.pl, messages.pl and types.pl). They need to be in the same folder. An easy way to install this library in your project is copying that files. Other way is using Git submodules to get this whole folder, and load the postgresql.pl file from there. 11 | 12 | ``` 13 | git submodule add https://github.com/aarroyoc/postgresql-prolog postgresql 14 | ``` 15 | 16 | # Usage 17 | 18 | The library provides four predicates: `connect/6`, `sql/3`, `query/3` and `query/4`. 19 | 20 | ``` 21 | connect(+User, +Password, +Host, +Port, +Database, -Connection) 22 | ``` 23 | Connects to a PostgreSQL server and tries to authenticate using `password` scheme. This is the only authentication method supported right now. Please, note that this auth method is not the default in some PostgreSQL setups, you changes are needed. If you're running PostgreSQL in Docker, you need to set the environment variable `POSTGRES_HOST_AUTH_METHOD` to `password`. 24 | 25 | ``` 26 | sql(+Connection, +QueryDSL, -Result) 27 | ``` 28 | Executes a SQL query using the Prolog DSL. This the **recommended** way to do queries as it is the **safest** (it escapes all strings). The DSL right now is limited to a few keywords. Feel free to open a PR to grow the DSL if you need it. The DSL is composed a list of commands, each command may contain different things. The DSL makes some incorrect queries invalid but it isn't a full fledged SQL syntax checker. 29 | 30 | Items of the DSL: 31 | 32 | * `select(col1, col2, ...)` - equivalent to `SELECT col1, col2, ... . Functions are allowed. For example: `select(sum(visits))` is valid and will generate `SELECT sum(visits)`. 33 | * `from(table)` - equivalent to `FROM table` 34 | * `natural_join(table)` - equivalent to `NATURAL JOIN table` 35 | * `join(table)` / `inner_join(table)` - equivalent to `INNER JOIN table`. Requires a `on` or `using` after. 36 | * `left_join(table)` / `left_outer_join` - equivalent to `LEFT OUTER JOIN table`. Requires a `on` or `using` after. 37 | * `right_join(table)` / `right_outer_join` - equivalent to `RIGHT OUTER JOIN table`. Requires a `on` or `using` after. 38 | * `full_join(table)` / `full_outer_join` - equivalent to `FULL OUTER JOIN table`. Requires a `on` or `using` after. 39 | * `on(Cond)` - equivalent to `ON Cond`. See `where` for details. 40 | * `using(col) - equivalent to `USING (col)`. 41 | * `where(Cond)` - equivalent to `WHERE Cond`. Cond is a Prolog condition. Meaning that you can use parens, AND is (,), OR is (;) and =, \=, >= and =< are used instead of the SQL operators. Strings that appear in the condition are escaped correctly. This is **safe**. 42 | * `group_by(col1)` - equivalent to GROUP BY col1. 43 | * `order_by(kind(col1), kind(col2),...)` - equivalent to ORDER BY col1 KIND, col2 KIND, .... kind must be either `asc` or `desc`. 44 | * `offset(N)` - equivalent to `OFFSET N ROWS`. 45 | * `fetch_first(N, type)` - equivalent to `FETCH FIRST N ROWS type`. Type can be `only (ONLY)` or `with_ties (WITH TIES)`. 46 | * `insert_into(table, [col1, col2,...])` - equivalent to `INSERT INTO table (col1, col2, ...)`. Must be followed by `values`. 47 | * `values(val1, val2, ...)` - equivalent to `VALUES (val1, val2, ...)`. Strings here are escaped so it's **safe**. 48 | * `returning(col1, col2, ...)` equivalent to `RETURNING col1, col2`. 49 | * `update(table)` - equivalent to `UPDATE table`. Must be followed by `set` 50 | * `set(Sets)` - equivalent to `SET Col1 = Val1, ...`. Similar to WHERE but only = is allowed. Optionally, you can add a `where+` after a `set`. 51 | * `delete(table)` - equivalent to `DELETE FROM table`. Must be followed by `where`. 52 | 53 | Examples: 54 | 55 | ``` 56 | QueryDSL = [select(title), from(posts), where(lang = "es"), order_by(desc(date)), offset(10), fetch_first(5, only)], 57 | SQL = "SELECT title FROM posts WHERE lang = $1 ORDER BY date DESC OFFSET 10 ROWS FETCH FIRST 5 ROWS ONLY" 58 | 59 | QueryDSL = [select('posts.title','author.name'), from(posts), join(author), on('author.author_id' = 'posts.author_id')] 60 | SQL = "SELECT posts.title,author.name FROM posts INNER JOIN author ON author.author_id = posts.author_id" 61 | 62 | QueryDSL = [select(title), from(posts), where((lang = "es";is_null(lang))), order_by(desc(date), asc(title))] 63 | SQL = "SELECT title FROM posts WHERE (lang = $1) OR (lang IS NULL) ORDER BY date DESC,title ASC" 64 | 65 | QueryDSL = [insert_into(test_table, [name]), values("test")] 66 | SQL = "INSERT INTO test_table (name) VALUES ($1)" 67 | 68 | QueryDSL = [update(post),set((lang = "es", price = 99)),where(lang = "fr")] 69 | SQL = "UPDATE post SET lang = $1,price = 99 WHERE lang = $2" 70 | 71 | ``` 72 | 73 | The Result var contains the result exection of the query. It can be: 74 | 75 | - error(ErrorString) 76 | - data(Rows) 77 | 78 | An OK response would be a data response with empty Rows. 79 | 80 | 81 | ``` 82 | query(+Connection, +Query, -Result) 83 | ``` 84 | Executes a SQL query string over a connection. Result can be: 85 | 86 | - ok 87 | - error(ErrorString) 88 | - data(ColumnDescription, Rows) 89 | 90 | ok is returned if the query doesn't output a table (INSERT, UPDATE, DELETE, CREATE TABLE, ...) and succeeds. 91 | 92 | error(ErrorString) is returned if an error is found. 93 | 94 | data(ColumnDescription, Rows) is returned when a query outputs a table (SELECT). ColumnDescription is a list of column names and Rows is a list of a list of each cell value. 95 | 96 | ``` 97 | query(+Connection, +QueryEscaped, +Data, -Result) 98 | ``` 99 | 100 | Executes a SQL query string over a connection. In contrast to `query/3`, here the query needs to be a template and the vars are passed in the Data list. This is safer than `query/3`. Result is the same as `sql/3`. 101 | 102 | 103 | # Examples 104 | 105 | ``` 106 | :- use_module('postgresql'). 107 | 108 | test :- 109 | postgresql:connect("postgres", "postgres", '127.0.0.1', 5432, "postgres", Connection), 110 | postgresql:query(Connection, "DROP TABLE IF EXISTS test_table", ok), 111 | postgresql:query(Connection, "CREATE TABLE test_table (id serial, name text)", ok), 112 | postgresql:sql(Connection, [insert_into(test_table, [name]), values("test")], data([])), 113 | postgresql:sql(Connection, [select(id, name), from(test_table), where(name = "test")], Rows), 114 | Rows = data([["1", "test"]]), 115 | postgresql:sql(Connection, [update(test_table), set(name = "test2"), where(id = 1)], data([])), 116 | postgresql:sql(Connection, [select(id, name), from(test_table), where(name = "test")], Rows2), 117 | Rows2 = data([]). 118 | ``` 119 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.6" 2 | services: 3 | postgres: 4 | image: postgres:15.3-alpine 5 | environment: 6 | POSTGRES_USER: postgres 7 | POSTGRES_PASSWORD: postgres 8 | POSTGRES_DB: postgres 9 | POSTGRES_HOST_AUTH_METHOD: password 10 | ports: 11 | - 5432:5432 12 | 13 | -------------------------------------------------------------------------------- /justfile: -------------------------------------------------------------------------------- 1 | test: psql-up && psql-down 2 | logtalk_tester -p scryer 3 | 4 | psql-up: 5 | docker-compose up -d postgres 6 | 7 | psql-down: 8 | docker-compose down 9 | -------------------------------------------------------------------------------- /messages.pl: -------------------------------------------------------------------------------- 1 | :- module(messages, [ 2 | startup_message/3, 3 | auth_message/2, 4 | password_message/2, 5 | auth_ok_message/1, 6 | query_message/2, 7 | notice_message/1, 8 | error_message/2, 9 | command_complete_message/1, 10 | empty_query_message/1, 11 | row_description_message/2, 12 | data_row_message/2, 13 | ready_for_query_message/1, 14 | parse_message/3, 15 | parse_complete_message/1, 16 | bind_message/2, 17 | bind_complete_message/1, 18 | execute_message/1, 19 | close_message/1, 20 | sync_message/1, 21 | flush_message/1 22 | ]). 23 | 24 | :- use_module(library(lists)). 25 | :- use_module(library(charsio)). 26 | :- use_module(library(dcgs)). 27 | :- use_module(library(format)). 28 | 29 | :- use_module('types'). 30 | 31 | % Message Formats 32 | % https://www.postgresql.org/docs/current/protocol-message-formats.html 33 | 34 | % StartupMessage 35 | startup_message(User, Database, Bytes) :- 36 | int32(196608, B1), % Version 37 | pstring("user", B2), 38 | pstring(User, B3), 39 | pstring("database", B4), 40 | pstring(Database, B5), 41 | phrase((B1, B2, B3, B4, B5, [0]), Bs), 42 | length(Bs, L), 43 | BytesLength is L + 4, 44 | int32(BytesLength, B0), 45 | append(B0, Bs, Bytes). 46 | 47 | % AuthenticationMD5Password 48 | auth_message(md5, Salt, Bytes) :- 49 | Bytes = [82,_,_,_,_|Bytes0], % Byte R 50 | Bytes0 = [B7, B6, B5, B4, B3, B2, B1, B0], 51 | int32(5, [B7, B6, B5, B4]), 52 | Salt = [B3, B2, B1, B0]. 53 | 54 | % AuthenticationCleartextPassword 55 | auth_message(password, Bytes) :- 56 | Bytes = [82,_,_,_,_|Bytes0], % Byte R 57 | Bytes0 = [B3, B2, B1, B0], 58 | int32(3, [B3, B2, B1, B0]). 59 | 60 | % PasswordMessage 61 | password_message(Password, Bytes) :- 62 | pstring(Password, Bytes0), 63 | length(Bytes0, L), 64 | RealLength is L + 4, 65 | int32(RealLength, Bytes1), 66 | append([112|Bytes1], Bytes0, Bytes). 67 | 68 | % AuthenticationOk 69 | auth_ok_message(Bytes) :- 70 | Bytes = [82,0,0,0,8,0,0,0,0]. % Byte R 71 | 72 | % Query 73 | query_message(Query, Bytes) :- 74 | pstring(Query, Bytes0), 75 | length(Bytes0, L), 76 | RealLength is L + 4, 77 | int32(RealLength, Bytes1), 78 | append([81|Bytes1], Bytes0, Bytes). 79 | 80 | % Parse 81 | parse_message(Query, NumberParams, Bytes) :- 82 | pstring("", Bytes1), 83 | pstring(Query, Bytes2), 84 | int16(NumberParams, Bytes3), 85 | findall(B, (length(X, NumberParams), member(N, X), N = 0, int32(N, B)), Bytes4), 86 | append(Bytes4, FBytes4), 87 | append([Bytes1, Bytes2, Bytes3, FBytes4], PreBytes), 88 | length(PreBytes, L), 89 | RealLength is L + 4, 90 | int32(RealLength, Bytes0), 91 | append([80|Bytes0], PreBytes, Bytes). % Byte P 92 | 93 | % ParseComplete 94 | parse_complete_message([49,_,_,_,_]). 95 | 96 | % Bind 97 | bind_message(Params, Bytes) :- 98 | pstring("", Bytes1), 99 | pstring("", Bytes2), 100 | int16(0, Bytes3), 101 | length(Params, NumberParams), 102 | int16(NumberParams, Bytes4), 103 | bind_message_params_bytes(Params, [], Bytes5), 104 | append([Bytes1, Bytes2, Bytes3, Bytes4, Bytes5, Bytes3], PreBytes), 105 | length(PreBytes, L), 106 | RealLength is L + 4, 107 | int32(RealLength, Bytes0), 108 | append([66|Bytes0], PreBytes, Bytes). % Byte B 109 | 110 | bind_message_params_bytes([], B, B). 111 | bind_message_params_bytes([null|Params], Bytes0, Bytes) :- 112 | int32(-1, B), 113 | append(Bytes0, B, Bytes1), 114 | bind_message_params_bytes(Params, Bytes1, Bytes). 115 | 116 | bind_message_params_bytes([Param|Params], Bytes0, Bytes) :- 117 | chars_utf8bytes(Param, B2), 118 | length(B2, L), 119 | int32(L, B1), 120 | append([B1, B2], B), 121 | append(Bytes0, B, Bytes1), 122 | bind_message_params_bytes(Params, Bytes1, Bytes). 123 | 124 | % BindComplete 125 | bind_complete_message([50,_,_,_,_]). 126 | 127 | % Execute 128 | execute_message(Bytes) :- 129 | int32(9, B1), 130 | pstring("", B2), 131 | int32(0, B3), 132 | append([[69|B1], B2, B3], Bytes). 133 | 134 | % Close 135 | close_message(Bytes) :- 136 | int32(6, B1), 137 | B2 = [83], 138 | pstring("", B3), 139 | append([[67|B1], B2, B3], Bytes). 140 | 141 | % Sync 142 | sync_message([83|B]) :- 143 | int32(4, B). 144 | 145 | % Flush 146 | flush_message([72|B]) :- 147 | int32(4, B). 148 | 149 | % ErrorResponse 150 | error_message(Error, Bytes) :- 151 | Bytes = [69,_,_,_,_,B0|Bytes0], % Byte E 152 | (B0 = 0 -> 153 | Error = "No error message" 154 | ; pstring(Error, Bytes0) 155 | ). 156 | 157 | % NoticeResponse 158 | notice_message(Bytes) :- 159 | Bytes = [78|_]. % Byte N 160 | 161 | % EmptyQueryResponse 162 | empty_query_message(Bytes) :- 163 | Bytes = [73,_,_,_,_]. % Byte I 164 | 165 | % CommandComplete 166 | command_complete_message(Bytes) :- 167 | Bytes = [67|_]. % Byte C 168 | 169 | % RowDescription 170 | row_description_message(Columns, Bytes) :- 171 | Bytes = [84,_,_,_,_|Bytes0], % Byte T 172 | Bytes0 = [B1, B0|Bytes1], 173 | int16(Fields, [B1, B0]), 174 | get_row_fields(Columns, Fields, Bytes1). 175 | 176 | split(Bytes, Separator, Bytes0, Bytes1) :- 177 | append(Bytes0, [Separator|Bytes1], Bytes). 178 | 179 | get_row_fields([], 0, _). 180 | get_row_fields([Column|Columns], Fields, Bytes) :- 181 | split(Bytes, 0, StringBytes, R), 182 | pstring(Column, StringBytes), 183 | R = [_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_|NewBytes], 184 | Fields0 is Fields - 1, 185 | get_row_fields(Columns, Fields0, NewBytes). 186 | 187 | % DataRow 188 | data_row_message(Columns, Bytes) :- 189 | Bytes = [68,_,_,_,_,B1,B0|Bytes0], % Byte D 190 | int16(Fields, [B1, B0]), 191 | get_fields(Columns, Fields, Bytes0). 192 | 193 | get_fields([], 0, _). 194 | get_fields([Column|Columns], Fields, Bytes) :- 195 | Bytes = [B3, B2, B1, B0|Bytes0], 196 | int32(Length, [B3, B2, B1, B0]), 197 | Length = 4294967295, % -1 198 | Column = null, 199 | Fields0 is Fields - 1, 200 | get_fields(Columns, Fields0, Bytes0). 201 | 202 | get_fields([Column|Columns], Fields, Bytes) :- 203 | Bytes = [B3, B2, B1, B0|Bytes0], 204 | int32(Length, [B3, B2, B1, B0]), 205 | Length \= 4294967295, % -1 206 | take(Length, Bytes0, ColumnBytes, NewBytes), 207 | chars_utf8bytes(Column, ColumnBytes), 208 | Fields0 is Fields - 1, 209 | get_fields(Columns, Fields0, NewBytes). 210 | 211 | take(N, Bytes, Bytes0, Bytes1) :- 212 | append(Bytes0, Bytes1, Bytes), 213 | length(Bytes0, N). 214 | 215 | % ReadyForQuery 216 | ready_for_query_message(Bytes) :- 217 | Bytes = [90|_]. % Byte Z 218 | -------------------------------------------------------------------------------- /postgresql.pl: -------------------------------------------------------------------------------- 1 | :- module(postgresql, [connect/6, query/3, query/4, sql/3]). 2 | 3 | :- use_module(library(lists)). 4 | :- use_module(library(charsio)). 5 | :- use_module(library(sockets)). 6 | 7 | 8 | :- use_module('messages'). 9 | :- use_module('sql_query'). 10 | :- use_module('types'). 11 | 12 | connect(User, Password, Host, Port, Database, postgresql(Stream)) :- 13 | socket_client_open(Host:Port, Stream, [type(binary)]), 14 | startup_message(User, Database, BytesStartup), 15 | put_bytes(Stream, BytesStartup), 16 | get_bytes(Stream, BytesAuth), 17 | auth_message(password, BytesAuth), 18 | password_message(Password, BytesPassword), 19 | put_bytes(Stream, BytesPassword), 20 | get_bytes(Stream, BytesOk), 21 | auth_ok_message(BytesOk), 22 | flush_bytes(Stream). 23 | 24 | flush_bytes(Stream) :- 25 | get_bytes(Stream, Bytes), 26 | ( 27 | Bytes = [90|_] -> 28 | true 29 | ; flush_bytes(Stream) 30 | ). 31 | 32 | query(postgresql(Stream), Query, Result) :- 33 | query_message(Query, BytesQuery), 34 | put_bytes(Stream, BytesQuery), 35 | get_bytes(Stream, BytesResponse), 36 | try_query_response(Stream, BytesResponse, Result). 37 | 38 | % after a query message, the following messages can be received 39 | % - CommandComplete 40 | % - RowDescription -> N DataRow 41 | % - EmptyQueryResponse 42 | % - ErrorResponse 43 | % - NoticeResponse 44 | % and then a ReadyForQuery message 45 | try_query_response(Stream, BytesResponse, Result) :- 46 | command_complete_message(BytesResponse),!, 47 | Result = ok, 48 | get_bytes(Stream, BytesEnd), 49 | ready_for_query_message(BytesEnd). 50 | 51 | try_query_response(Stream, BytesResponse, Result) :- 52 | row_description_message(ColumnsDescription, BytesResponse),!, 53 | % then zero or more data rows 54 | get_bytes(Stream, BytesData), 55 | get_data_rows(Stream, ColumnsData, BytesData), 56 | Result = data(ColumnsDescription, ColumnsData). 57 | % until we get a command complete message 58 | 59 | try_query_response(Stream, BytesResponse, Result) :- 60 | empty_query_message(BytesResponse),!, 61 | Result = [], 62 | get_bytes(Stream, BytesEnd), 63 | ready_for_query_message(BytesEnd). 64 | 65 | try_query_response(Stream, BytesResponse, Result) :- 66 | error_message(Error, BytesResponse),!, 67 | Result = error(Error), 68 | get_bytes(Stream, BytesEnd), 69 | ready_for_query_message(BytesEnd). 70 | 71 | try_query_response(Stream, BytesResponse, Result) :- 72 | notice_message(BytesResponse),!, 73 | get_bytes(Stream, BytesResponse0), 74 | try_query_response(Stream, BytesResponse0, Result). 75 | 76 | get_data_rows(Stream, [], BytesData) :- 77 | command_complete_message(BytesData),!, 78 | get_bytes(Stream, BytesData0), 79 | ready_for_query_message(BytesData0). 80 | 81 | get_data_rows(Stream, [Column|Columns], BytesData) :- 82 | data_row_message(Column, BytesData),!, 83 | get_bytes(Stream, BytesData0), 84 | get_data_rows(Stream, Columns, BytesData0). 85 | 86 | % Extended Query. Safer 87 | query(postgresql(Stream), Query, Params, Result) :- 88 | length(Params, NumberParams), 89 | parse_message(Query, NumberParams, QueryBytes), 90 | put_bytes(Stream, QueryBytes), 91 | flush_message(FlushBytes), 92 | put_bytes(Stream, FlushBytes), 93 | get_bytes(Stream, ResponseBytes), 94 | try_parse_response(Stream, ResponseBytes, Params, Result). 95 | 96 | try_parse_response(Stream, BytesData, Params, Result) :- 97 | parse_complete_message(BytesData),!, 98 | bind_message(Params, BindBytes), 99 | put_bytes(Stream, BindBytes), 100 | flush_message(FlushBytes), 101 | put_bytes(Stream, FlushBytes), 102 | get_bytes(Stream, ResponseBytes), 103 | try_bind_response(Stream, ResponseBytes, Result). 104 | 105 | try_parse_response(Stream, BytesResponse, _, Result) :- 106 | error_message(Error, BytesResponse),!, 107 | Result = error(Error), 108 | sync_message(SyncBytes), 109 | put_bytes(Stream, SyncBytes), 110 | get_bytes(Stream, BytesEnd), 111 | ready_for_query_message(BytesEnd). 112 | 113 | try_bind_response(Stream, BytesData, Result) :- 114 | bind_complete_message(BytesData),!, 115 | execute_message(ExecuteBytes), 116 | put_bytes(Stream, ExecuteBytes), 117 | flush_message(FlushBytes), 118 | put_bytes(Stream, FlushBytes), 119 | get_bytes(Stream, ResponseBytes), 120 | try_execute_response(Stream, ResponseBytes, Result). 121 | 122 | try_bind_response(Stream, BytesResponse, _, Result) :- 123 | error_message(Error, BytesResponse),!, 124 | Result = error(Error), 125 | sync_message(SyncBytes), 126 | put_bytes(Stream, SyncBytes), 127 | get_bytes(Stream, BytesEnd), 128 | ready_for_query_message(BytesEnd). 129 | 130 | try_execute_response(Stream, BytesResponse, Result) :- 131 | ext_get_data_rows(Stream, ColumnsData, BytesResponse), 132 | Result = data(ColumnsData). 133 | 134 | try_execute_response(Stream, BytesResponse, Result) :- 135 | empty_query_message(BytesResponse),!, 136 | Result = [], 137 | get_bytes(Stream, BytesEnd), 138 | ready_for_query_message(BytesEnd). 139 | 140 | try_execute_response(Stream, BytesResponse, Result) :- 141 | error_message(Error, BytesResponse),!, 142 | Result = error(Error), 143 | get_bytes(Stream, BytesEnd), 144 | ready_for_query_message(BytesEnd). 145 | 146 | ext_get_data_rows(Stream, [], BytesData) :- 147 | command_complete_message(BytesData),!, 148 | sync_message(SyncBytes), 149 | put_bytes(Stream, SyncBytes), 150 | get_bytes(Stream, BytesData0), 151 | ready_for_query_message(BytesData0). 152 | 153 | ext_get_data_rows(Stream, [Column|Columns], BytesData) :- 154 | data_row_message(Column, BytesData),!, 155 | get_bytes(Stream, BytesData0), 156 | ext_get_data_rows(Stream, Columns, BytesData0). 157 | 158 | 159 | % https://www.postgresql.org/docs/current/protocol-flow.html#id-1.10.5.7.3 160 | 161 | get_bytes(Stream, Bytes) :- 162 | get_byte(Stream, BType), 163 | get_byte(Stream, B3), 164 | get_byte(Stream, B2), 165 | get_byte(Stream, B1), 166 | get_byte(Stream, B0), 167 | int32(Length, [B3, B2, B1, B0]), 168 | RemainingBytes is Length - 4, 169 | get_bytes(Stream, RemainingBytes, Bytes0), 170 | append([BType, B3, B2, B1, B0], Bytes0, Bytes), 171 | !. 172 | 173 | get_bytes(_, 0, []). 174 | get_bytes(Stream, RemainingBytes, [B|Bytes]) :- 175 | get_byte(Stream, B), 176 | RemainingBytes1 is RemainingBytes - 1, 177 | get_bytes(Stream, RemainingBytes1, Bytes). 178 | 179 | put_bytes(_, []). 180 | put_bytes(Stream, [Byte|Bytes]) :- 181 | put_byte(Stream, Byte), 182 | put_bytes(Stream, Bytes), 183 | !. 184 | 185 | sql(Connection, Query, Result) :- 186 | sql_query(Query, TextQuery, Vars), 187 | keysort(Vars, SortedVars), 188 | maplist(pair_value, SortedVars, QueryVars), 189 | query(Connection, TextQuery, QueryVars, Result). 190 | 191 | pair_value(_-B, B). 192 | -------------------------------------------------------------------------------- /sql_query.pl: -------------------------------------------------------------------------------- 1 | :- module(sql_query, [sql_query/3]). 2 | 3 | :- use_module(library(dcgs)). 4 | :- use_module(library(format)). 5 | :- use_module(library(lists)). 6 | :- use_module(library(si)). 7 | 8 | % Documentation 9 | % SQL-92 BNF: https://ronsavage.github.io/SQL/sql-92.bnf.html 10 | % This translation doesn't try to be complete. Just enough for basic use cases. 11 | 12 | sql_query(DSLQuery, TextQuery, Vars) :- 13 | phrase(sql_query_select(DSLQuery, Vars), TextQuery). 14 | 15 | sql_query(DSLQuery, TextQuery, Vars) :- 16 | phrase(sql_query_insert(DSLQuery, Vars), TextQuery). 17 | 18 | sql_query(DSLQuery, TextQuery, Vars) :- 19 | phrase(sql_query_update(DSLQuery, Vars), TextQuery). 20 | 21 | sql_query(DSLQuery, TextQuery, Vars) :- 22 | phrase(sql_query_delete(DSLQuery, Vars), TextQuery). 23 | 24 | sql_query_select([Select|Rest], Vars) --> 25 | { Select =.. [select|Args] }, 26 | "SELECT ", 27 | quoted_comma_separated_list(Args), 28 | " ", 29 | sql_query_from(Rest, Vars). 30 | 31 | quoted_comma_separated_list([Arg]) --> 32 | format_("~w", [Arg]). 33 | quoted_comma_separated_list([Arg|Args]) --> 34 | format_("~w,", [Arg]), 35 | quoted_comma_separated_list(Args). 36 | 37 | sql_query_from([from(Table)], [] ) --> 38 | "FROM ", 39 | format_("~w", [Table]). 40 | 41 | sql_query_from([from(Table)|Rest], Vars) --> 42 | "FROM ", 43 | format_("~w", [Table]), 44 | " ", 45 | sql_query_join(Rest, Vars), 46 | { var(Vars) -> Vars = []; true }. 47 | 48 | sql_query_join([join(Table)|Rest], Vars) --> 49 | sql_query_join([inner_join(Table)|Rest], Vars). 50 | 51 | sql_query_join([inner_join(Table)|Rest], Vars) --> 52 | "INNER JOIN ", 53 | format_("~w", [Table]), 54 | " ", 55 | sql_query_join_second(Rest, Vars). 56 | 57 | sql_query_join([left_join(Table)|Rest], Vars) --> 58 | sql_query_join([left_outer_join(Table)|Rest], Vars). 59 | 60 | sql_query_join([left_outer_join(Table)|Rest], Vars) --> 61 | "LEFT OUTER JOIN ", 62 | format_("~w", [Table]), 63 | " ", 64 | sql_query_join_second(Rest, Vars). 65 | 66 | sql_query_join([right_join(Table)|Rest], Vars) --> 67 | sql_query_join([right_outer_join(Table)|Rest], Vars). 68 | 69 | sql_query_join([right_outer_join(Table)|Rest], Vars) --> 70 | "RIGHT OUTER JOIN ", 71 | format_("~w", [Table]), 72 | " ", 73 | sql_query_join_second(Rest, Vars). 74 | 75 | sql_query_join([full_join(Table)|Rest], Vars) --> 76 | sql_query_join([full_outer_join(Table)|Rest], Vars). 77 | 78 | sql_query_join([full_outer_join(Table)|Rest], Vars) --> 79 | "FULL OUTER JOIN ", 80 | format_("~w", [Table]), 81 | " ", 82 | sql_query_join_second(Rest, Vars). 83 | 84 | sql_query_join([natural_join(Table)], []) --> 85 | "NATURAL JOIN ", 86 | format_("~w", [Table]). 87 | 88 | sql_query_join([natural_join(Table)|Rest], Vars) --> 89 | "NATURAL JOIN ", 90 | format_("~w", [Table]), 91 | " ", 92 | sql_query_join(Rest, Vars). 93 | 94 | sql_query_join(Rest, Vars) --> 95 | sql_query_where(Rest, Vars). 96 | 97 | sql_query_join_second([on(Cond)], Vars) --> 98 | "ON ", 99 | sql_cond(Cond, [], Vars). 100 | 101 | sql_query_join_second([on(Cond)|Rest], Vars) --> 102 | "ON ", 103 | sql_cond(Cond, [], Vars0), 104 | " ", 105 | sql_query_join(Rest, Vars1), 106 | { append(Vars0, Vars1, Vars) }. 107 | 108 | sql_query_join_second([using(Col)], []) --> 109 | "USING (", 110 | format_("~w", [Col]), 111 | ")". 112 | 113 | sql_query_join_second([using(Col)|Rest], Vars) --> 114 | "USING (", 115 | format_("~w", [Col]), 116 | ") ", 117 | sql_query_join(Rest, Vars). 118 | 119 | sql_query_where([where(Cond)], Vars) --> 120 | "WHERE ", 121 | sql_cond(Cond, [], Vars). 122 | 123 | sql_query_where([where(Cond)|Rest], Vars) --> 124 | "WHERE ", 125 | sql_cond(Cond, [], Vars), 126 | " ", 127 | sql_query_group_by(Rest). 128 | 129 | sql_query_where(Rest, []) --> 130 | sql_query_group_by(Rest). 131 | 132 | sql_cond((A,B), Vars0, Vars) --> 133 | "(", 134 | sql_cond(A, Vars0, Vars1), 135 | ") AND (", 136 | sql_cond(B, Vars1, Vars), 137 | ")". 138 | 139 | sql_cond((A;B), Vars0, Vars) --> 140 | "(", 141 | sql_cond(A, Vars0, Vars1), 142 | ") OR (", 143 | sql_cond(B, Vars1, Vars), 144 | ")". 145 | 146 | sql_cond((\+ A), Vars0, Vars) --> 147 | "NOT (", 148 | sql_cond(A, Vars0, Vars), 149 | ")". 150 | 151 | sql_cond(is_null(A), Vars0, Vars) --> 152 | { sql_var(A, VarA, Vars0, Vars) }, 153 | format_("~w IS NULL", [VarA]). 154 | 155 | sql_cond(A = B, Vars0, Vars) --> 156 | { sql_var(A, VarA, Vars0, Vars1) }, 157 | { sql_var(B, VarB, Vars1, Vars) }, 158 | format_("~w = ~w", [VarA, VarB]). 159 | 160 | sql_cond(A \= B, Vars0, Vars) --> 161 | { sql_var(A, VarA, Vars0, Vars1) }, 162 | { sql_var(B, VarB, Vars1, Vars) }, 163 | format_("~w <> ~w", [VarA, VarB]). 164 | 165 | sql_cond(A > B, Vars0, Vars) --> 166 | { sql_var(A, VarA, Vars0, Vars1) }, 167 | { sql_var(B, VarB, Vars1, Vars) }, 168 | format_("~w > ~w", [VarA, VarB]). 169 | 170 | sql_cond(A < B, Vars0, Vars) --> 171 | { sql_var(A, VarA, Vars0, Vars1) }, 172 | { sql_var(B, VarB, Vars1, Vars) }, 173 | format_("~w < ~w", [VarA, VarB]). 174 | 175 | sql_cond(A >= B, Vars0, Vars) --> 176 | { sql_var(A, VarA, Vars0, Vars1) }, 177 | { sql_var(B, VarB, Vars1, Vars) }, 178 | format_("~w >= ~w", [VarA, VarB]). 179 | 180 | sql_cond(A =< B, Vars0, Vars) --> 181 | { sql_var(A, VarA, Vars0, Vars1) }, 182 | { sql_var(B, VarB, Vars1, Vars) }, 183 | format_("~w <= ~w", [VarA, VarB]). 184 | 185 | 186 | sql_var(Var, OutVar, Vars0, Vars) :- 187 | chars_si(Var), 188 | length(Vars0, N0), 189 | N is N0 + 1, 190 | number_chars(N, Cs), 191 | atom_chars(OutVar, ['$'|Cs]), 192 | Vars = [N-Var|Vars0]. 193 | 194 | sql_var(Var, OutVar, Vars0, Vars) :- 195 | ( atom_si(Var) ; integer_si(Var)), 196 | Var = OutVar, 197 | Vars0 = Vars. 198 | 199 | sql_query_group_by([GroupBy]) --> 200 | { GroupBy =.. [group_by|Args] }, 201 | "GROUP BY ", 202 | quoted_comma_separated_list(Args). 203 | 204 | sql_query_group_by([GroupBy|Rest]) --> 205 | { GroupBy =.. [group_by|Args] }, 206 | "GROUP BY ", 207 | quoted_comma_separated_list(Args), 208 | sql_query_order_by(Rest). 209 | 210 | sql_query_group_by(Rest) --> 211 | sql_query_order_by(Rest). 212 | 213 | sql_query_order_by([OrderBy]) --> 214 | { OrderBy =.. [order_by|Args0] }, 215 | "ORDER BY ", 216 | { order_args(Args0, Args) }, 217 | quoted_comma_separated_list(Args). 218 | 219 | sql_query_order_by([OrderBy|Rest]) --> 220 | { OrderBy =.. [order_by|Args0] }, 221 | "ORDER BY ", 222 | { order_args(Args0, Args) }, 223 | quoted_comma_separated_list(Args), 224 | " ", 225 | sql_query_offset(Rest). 226 | 227 | sql_query_order_by(Rest) --> 228 | sql_query_offset(Rest). 229 | 230 | sql_query_offset([offset(N)]) --> 231 | "OFFSET ", 232 | format_("~w", [N]), 233 | " ROWS". 234 | 235 | sql_query_offset([offset(N)|Rest]) --> 236 | "OFFSET ", 237 | format_("~w", [N]), 238 | " ROWS ", 239 | sql_query_fetch_first(Rest). 240 | 241 | sql_query_offset(Rest) --> 242 | sql_query_fetch_first(Rest). 243 | 244 | sql_query_fetch_first([fetch_first(N, only)]) --> 245 | "FETCH FIRST ", 246 | format_("~w", [N]), 247 | " ROWS ONLY". 248 | 249 | sql_query_fetch_first([fetch_first(N, with_ties)]) --> 250 | "FETCH FIRST ", 251 | format_("~w", [N]), 252 | " ROWS WITH TIES". 253 | 254 | order_args([], []). 255 | order_args([asc(Arg0)|Rest0], [Arg|Rest]) :- 256 | atom_concat(Arg0, ' ASC', Arg), 257 | order_args(Rest0, Rest). 258 | order_args([desc(Arg0)|Rest0], [Arg|Rest]) :- 259 | atom_concat(Arg0, ' DESC', Arg), 260 | order_args(Rest0, Rest). 261 | 262 | % INSERT 263 | 264 | sql_query_insert([insert_into(Table, Cols)|Values], Vars) --> 265 | "INSERT INTO ", 266 | format_("~w", [Table]), 267 | " (", 268 | quoted_comma_separated_list(Cols), 269 | ") ", 270 | sql_query_insert_values(Values, Vars). 271 | 272 | sql_query_insert_values([Values0|Next], Vars) --> 273 | { Values0 =.. [values|Values] }, 274 | "VALUES (", 275 | { values_args(Values, Args, [], Vars0) }, 276 | quoted_comma_separated_list(Args), 277 | ") ", 278 | sql_query_insert_on_conflict(Next, Vars1), 279 | { append(Vars0, Vars1, Vars) }. 280 | 281 | sql_query_insert_values([Values0], Vars) --> 282 | { Values0 =.. [values|Values] }, 283 | "VALUES (", 284 | { values_args(Values, Args, [], Vars) }, 285 | quoted_comma_separated_list(Args), 286 | ")". 287 | 288 | sql_query_insert_on_conflict([Values0|Next], Vars) --> 289 | { Values0 =.. [on_conflict_do_update|Cols] }, 290 | "ON CONFLICT (", 291 | quoted_comma_separated_list(Cols), 292 | ") DO UPDATE ", 293 | sql_query_insert_do_update_set(Next, Vars). 294 | 295 | sql_query_insert_on_conflict([Values0|Next], []) --> 296 | { Values0 =.. [on_conflict_do_nothing|Cols] }, 297 | "ON CONFLICT (", 298 | quoted_comma_separated_list(Cols), 299 | ") DO NOTHING ", 300 | sql_query_insert_returning(Next). 301 | 302 | sql_query_insert_on_conflict([on_conflict_do_nothing|Next], []) --> 303 | "ON CONFLICT DO NOTHING ", 304 | sql_query_insert_returning(Next). 305 | 306 | sql_query_insert_on_conflict([Values0], []) --> 307 | { Values0 =.. [on_conflict_do_nothing|Cols] }, 308 | "ON CONFLICT (", 309 | quoted_comma_separated_list(Cols), 310 | ") DO NOTHING". 311 | 312 | sql_query_insert_on_conflict([on_conflict_do_nothing], []) --> 313 | "ON CONFLICT DO NOTHING". 314 | 315 | sql_query_insert_on_conflict(Rest, []) --> 316 | sql_query_insert_returning(Rest). 317 | 318 | sql_query_insert_do_update_set([set(Cond)], Vars) --> 319 | "SET ", 320 | sql_set(Cond, [], Vars). 321 | 322 | sql_query_insert_do_update_set([set(Cond) | Rest], Vars) --> 323 | "SET ", 324 | sql_set(Cond, [], Vars), 325 | " ", 326 | sql_query_insert_returning(Rest). 327 | 328 | sql_query_insert_returning([Returning0]) --> 329 | { Returning0 =.. [returning|Columns] }, 330 | "RETURNING ", 331 | quoted_comma_separated_list(Columns). 332 | 333 | values_args([], [], X, X). 334 | values_args([Value|Values], [Arg|Args], Vars0, Vars) :- 335 | sql_var(Value, Arg, Vars0, Vars1), 336 | values_args(Values, Args, Vars1, Vars). 337 | 338 | % UPDATE 339 | 340 | sql_query_update([update(Table)|Rest], Vars) --> 341 | "UPDATE ", 342 | format_("~w", [Table]), 343 | " ", 344 | sql_query_update_set(Rest, Vars). 345 | 346 | sql_query_update_set([set(Cond)], Vars) --> 347 | "SET ", 348 | sql_set(Cond, [], Vars). 349 | 350 | sql_query_update_set([set(Cond)|Rest], Vars) --> 351 | "SET ", 352 | sql_set(Cond, [], Vars1), 353 | " ", 354 | sql_query_update_where(Rest, Vars1, Vars). 355 | 356 | sql_query_update_where([where(Cond)], Vars0, Vars) --> 357 | "WHERE ", 358 | sql_cond(Cond, Vars0, Vars). 359 | 360 | sql_set((A,B), Vars0, Vars) --> 361 | sql_set(A, Vars0, Vars1), 362 | ",", 363 | sql_set(B, Vars1, Vars). 364 | 365 | sql_set(A = B, Vars0, Vars) --> 366 | { sql_var(A, VarA, Vars0, Vars1) }, 367 | { sql_var(B, VarB, Vars1, Vars) }, 368 | format_("~w = ~w", [VarA, VarB]). 369 | 370 | % DELETE 371 | 372 | sql_query_delete([delete(Table)|Rest], Vars) --> 373 | "DELETE FROM ", 374 | format_("~w", [Table]), 375 | " ", 376 | sql_query_delete_where(Rest, Vars). 377 | 378 | sql_query_delete_where([where(Cond)], Vars) --> 379 | "WHERE ", 380 | sql_cond(Cond, [], Vars). 381 | -------------------------------------------------------------------------------- /tester.lgt: -------------------------------------------------------------------------------- 1 | :- initialization(( 2 | set_logtalk_flag(report, warnings), 3 | set_logtalk_flag(unknown_entities, silent), 4 | logtalk_load(lgtunit(loader)), 5 | logtalk_load('tests', [hook(lgtunit)]), 6 | tests::run 7 | )). -------------------------------------------------------------------------------- /tests.lgt: -------------------------------------------------------------------------------- 1 | :- use_module(postgresql). 2 | :- use_module(sql_query). 3 | 4 | :- object(tests, extends(lgtunit)). 5 | 6 | test(trivial) :- true. 7 | test(password_connection_ok) :- postgresql:connect("postgres", "postgres", '127.0.0.1', 5432, "postgres", _). 8 | fails(password_connection_fail) :- postgresql:connect("postgres", "invalid", '127.0.0.1', 5432, "postgres", _). 9 | 10 | test(create_table_insert_and_select) :- 11 | postgresql:connect("postgres", "postgres", '127.0.0.1', 5432, "postgres", Connection), 12 | postgresql:query(Connection, "DROP TABLE IF EXISTS test_table", ok), 13 | postgresql:query(Connection, "CREATE TABLE test_table (id serial, name text)", ok), 14 | postgresql:query(Connection, "INSERT INTO test_table (name) VALUES ('test')", ok), 15 | postgresql:query(Connection, "SELECT * FROM test_table", Rows), 16 | Rows = data(["id", "name"], [["1", "test"]]). 17 | 18 | test(table_already_exists) :- 19 | postgresql:connect("postgres", "postgres", '127.0.0.1', 5432, "postgres", Connection), 20 | postgresql:query(Connection, "DROP TABLE IF EXISTS test_table", ok), 21 | postgresql:query(Connection, "CREATE TABLE test_table (id serial, name text)", ok), 22 | postgresql:query(Connection, "CREATE TABLE test_table (id serial, name text)", error(_)). 23 | 24 | 25 | test(update_data) :- 26 | postgresql:connect("postgres", "postgres", '127.0.0.1', 5432, "postgres", Connection), 27 | postgresql:query(Connection, "DROP TABLE IF EXISTS test_table", ok), 28 | postgresql:query(Connection, "CREATE TABLE test_table (id serial, name text)", ok), 29 | postgresql:query(Connection, "INSERT INTO test_table (name) VALUES ('test')", ok), 30 | postgresql:query(Connection, "SELECT * FROM test_table", Rows), 31 | Rows = data(["id", "name"], [["1", "test"]]), 32 | postgresql:query(Connection, "UPDATE test_table SET name = 'test2' WHERE id = 1", ok), 33 | postgresql:query(Connection, "SELECT * FROM test_table", Rows2), 34 | Rows2 = data(["id", "name"], [["1", "test2"]]). 35 | 36 | test(extended_query) :- 37 | postgresql:connect("postgres", "postgres", '127.0.0.1', 5432, "postgres", Connection), 38 | postgresql:query(Connection, "DROP TABLE IF EXISTS test_table", ok), 39 | postgresql:query(Connection, "CREATE TABLE test_table (id serial, name text)", ok), 40 | postgresql:query(Connection, "INSERT INTO test_table (name) VALUES ('test')", ok), 41 | postgresql:query(Connection, "SELECT * FROM test_table WHERE name = $1", ["test"], Rows), 42 | Rows = data([["1", "test"]]), 43 | postgresql:query(Connection, "UPDATE test_table SET name = 'test2' WHERE id = 1", ok), 44 | postgresql:query(Connection, "SELECT * FROM test_table WHERE name = $1", ["test"], Rows2), 45 | Rows2 = data([]). 46 | 47 | test(sql_query_simple) :- 48 | sql_query:sql_query([select(title,post), from(posts)], "SELECT title,post FROM posts", []). 49 | 50 | test(sql_query_group_by) :- 51 | sql_query:sql_query( 52 | [select(sum(visits)), from(posts), where(lang = "es"), group_by(title)], 53 | "SELECT sum(visits) FROM posts WHERE lang = $1 GROUP BY title", 54 | [1-"es"] 55 | ). 56 | 57 | test(sql_query_order_by) :- 58 | sql_query:sql_query( 59 | [select(title,content), from(posts), order_by(desc(date), asc(title))], 60 | "SELECT title,content FROM posts ORDER BY date DESC,title ASC", 61 | [] 62 | ). 63 | 64 | test(sql_query_join) :- 65 | sql_query:sql_query( 66 | [select('posts.title','author.name'), from(posts), join(author), on('author.author_id' = 'posts.author_id')], 67 | "SELECT posts.title,author.name FROM posts INNER JOIN author ON author.author_id = posts.author_id", 68 | [] 69 | ). 70 | 71 | test(sql_query_join_where) :- 72 | sql_query:sql_query( 73 | [select('posts.title','author.name'), from(posts), join(author), on('author.author_id' = 'posts.author_id'), where(lang = "es")], 74 | "SELECT posts.title,author.name FROM posts INNER JOIN author ON author.author_id = posts.author_id WHERE lang = $1", 75 | [1-"es"] 76 | ). 77 | 78 | test(sql_query_join_using) :- 79 | sql_query:sql_query( 80 | [select('posts.title','author.name'), from(posts), join(author), using(author_id)], 81 | "SELECT posts.title,author.name FROM posts INNER JOIN author USING (author_id)", 82 | [] 83 | ). 84 | 85 | test(full_join) :- 86 | sql_query:sql_query( 87 | [select('posts.title','author.name'), from(posts), full_join(author), using(author_id)], 88 | "SELECT posts.title,author.name FROM posts FULL OUTER JOIN author USING (author_id)", 89 | [] 90 | ). 91 | 92 | test(multiple_join) :- 93 | sql_query:sql_query( 94 | [select('posts.title','author.name'), from(posts), full_join(author), using(author_id), join(comment), on('comment.id' = 5)], 95 | "SELECT posts.title,author.name FROM posts FULL OUTER JOIN author USING (author_id) INNER JOIN comment ON comment.id = 5", 96 | [] 97 | ). 98 | 99 | test(natural_join) :- 100 | sql_query:sql_query( 101 | [select('posts.title','author.name'), from(posts), natural_join(author), where(lang = "es"), order_by(desc(date))], 102 | "SELECT posts.title,author.name FROM posts NATURAL JOIN author WHERE lang = $1 ORDER BY date DESC", 103 | [1-"es"] 104 | ). 105 | 106 | test(sql_query_or) :- 107 | sql_query:sql_query( 108 | [select(title), from(posts), where((lang = "es";is_null(lang))), order_by(desc(date), asc(title))], 109 | "SELECT title FROM posts WHERE (lang = $1) OR (lang IS NULL) ORDER BY date DESC,title ASC", 110 | [1-"es"] 111 | ). 112 | 113 | test(fetch_first) :- 114 | sql_query:sql_query( 115 | [select(title), from(posts), where(lang = "es"), order_by(desc(date)), offset(10), fetch_first(5, only)], 116 | "SELECT title FROM posts WHERE lang = $1 ORDER BY date DESC OFFSET 10 ROWS FETCH FIRST 5 ROWS ONLY", 117 | [1-"es"] 118 | ). 119 | 120 | test(insert_into) :- 121 | sql_query:sql_query( 122 | [insert_into(posts, [title, content]), values("Mi nuevo Libro", "Luna de Plutón")], 123 | "INSERT INTO posts (title,content) VALUES ($1,$2)", 124 | [2-"Luna de Plutón", 1-"Mi nuevo Libro"] 125 | ). 126 | 127 | test(insert_into_on_conflict_do_update) :- 128 | sql_query:sql_query( 129 | [insert_into(posts, [title, content]), values("Mi nuevo Libro", "Luna de Plutón"), on_conflict_do_update(title), set(content='EXCLUDED.content')], 130 | "INSERT INTO posts (title,content) VALUES ($1,$2) ON CONFLICT (title) DO UPDATE SET content = EXCLUDED.content", 131 | [2-"Luna de Plutón", 1-"Mi nuevo Libro"] 132 | ). 133 | 134 | test(insert_into_on_conflict_do_nothing) :- 135 | sql_query:sql_query( 136 | [insert_into(posts, [title, content]), values("Mi nuevo Libro", "Luna de Plutón"), on_conflict_do_nothing], 137 | "INSERT INTO posts (title,content) VALUES ($1,$2) ON CONFLICT DO NOTHING", 138 | [2-"Luna de Plutón", 1-"Mi nuevo Libro"] 139 | ). 140 | 141 | test(insert_into_on_conflict_do_nothing_with_cols) :- 142 | sql_query:sql_query( 143 | [insert_into(posts, [title, content]), values("Mi nuevo Libro", "Luna de Plutón"), on_conflict_do_nothing(title)], 144 | "INSERT INTO posts (title,content) VALUES ($1,$2) ON CONFLICT (title) DO NOTHING", 145 | [2-"Luna de Plutón", 1-"Mi nuevo Libro"] 146 | ). 147 | 148 | test(sql_query_update) :- 149 | sql_query:sql_query( 150 | [update(post),set((lang = "es", price = 99))], 151 | "UPDATE post SET lang = $1,price = 99", 152 | [1-"es"] 153 | ). 154 | 155 | test(sql_query_update) :- 156 | sql_query:sql_query( 157 | [update(post),set((lang = "es", price = 99)),where(lang = "fr")], 158 | "UPDATE post SET lang = $1,price = 99 WHERE lang = $2", 159 | [2-"fr", 1-"es"] 160 | ). 161 | 162 | test(sql_query_delete) :- 163 | sql_query:sql_query( 164 | [delete(post),where(lang = "fr")], 165 | "DELETE FROM post WHERE lang = $1", 166 | [1-"fr"] 167 | ). 168 | 169 | test(sql_query) :- 170 | postgresql:connect("postgres", "postgres", '127.0.0.1', 5432, "postgres", Connection), 171 | postgresql:query(Connection, "DROP TABLE IF EXISTS test_table", ok), 172 | postgresql:query(Connection, "CREATE TABLE test_table (id serial, name text)", ok), 173 | postgresql:sql(Connection, [insert_into(test_table, [name]), values("test")], data([])), 174 | postgresql:sql(Connection, [select(id, name), from(test_table), where(name = "test")], Rows), 175 | Rows = data([["1", "test"]]), 176 | postgresql:sql(Connection, [update(test_table), set(name = "test2"), where(id = 1)], data([])), 177 | postgresql:sql(Connection, [select(id, name), from(test_table), where(name = "test")], Rows2), 178 | Rows2 = data([]). 179 | 180 | test(sql_query_2) :- 181 | postgresql:connect("postgres", "postgres", '127.0.0.1', 5432, "postgres", Connection), 182 | postgresql:query(Connection, "DROP TABLE IF EXISTS famous", ok), 183 | postgresql:query(Connection, "DROP TABLE IF EXISTS country", ok), 184 | postgresql:query(Connection, "CREATE TABLE country (iso_code varchar(2) PRIMARY KEY, name text)", ok), 185 | postgresql:query(Connection, "CREATE TABLE famous (id serial PRIMARY KEY, name text, country varchar(2) REFERENCES country(iso_code), year int)", ok), 186 | postgresql:sql(Connection, [insert_into(country, [iso_code, name]), values("ES", "España")], data([])), 187 | postgresql:sql(Connection, [insert_into(country, [iso_code, name]), values("PT", "Portugal")], data([])), 188 | postgresql:sql(Connection, [insert_into(famous, [name, country, year]), values("Miguel de Cervantes", "ES", 1547)], data([])), 189 | postgresql:sql(Connection, [insert_into(famous, [name, country, year]), values("Magallanes", "PT", 1480)], data([])), 190 | postgresql:sql(Connection, [insert_into(famous, [name, country, year]), values("Picasso", "ES", 1881), returning(name, country)], data([["Picasso", "ES"]])), 191 | postgresql:sql(Connection, [select('famous.name','country.name'),from(famous),join(country),on('famous.country' = 'country.iso_code'),where((year > 1500,year < 2000)),order_by(asc(year))], Result), 192 | Result = data([["Miguel de Cervantes", "España"], ["Picasso", "España"]]). 193 | 194 | 195 | :- end_object. 196 | -------------------------------------------------------------------------------- /types.pl: -------------------------------------------------------------------------------- 1 | :- module(types, [int16/2, int32/2, pstring/2]). 2 | 3 | :- use_module(library(lists)). 4 | :- use_module(library(charsio)). 5 | 6 | % Message Types 7 | % https://www.postgresql.org/docs/current/protocol-message-types.html 8 | 9 | int32(Number, [B3, B2, B1, B0]) :- 10 | var(Number), 11 | Number is (B3 << 24) + (B2 << 16) + (B1 << 8) + B0. 12 | 13 | int32(Number, [B3, B2, B1, B0]) :- 14 | integer(Number), 15 | B0 is Number /\ 255, 16 | B1 is (Number >> 8) /\ 255, 17 | B2 is (Number >> 16) /\ 255, 18 | B3 is (Number >> 24) /\ 255. 19 | 20 | int16(Number, [B1, B0]) :- 21 | var(Number), 22 | Number is (B1 << 8) + B0. 23 | 24 | int16(Number, [B1, B0]) :- 25 | integer(Number), 26 | B0 is Number /\ 255, 27 | B1 is (Number >> 8) /\ 255. 28 | 29 | pstring(String, Bytes) :- 30 | var(Bytes), 31 | chars_utf8bytes(String, Bytes0), 32 | append(Bytes0, [0], Bytes). 33 | 34 | pstring(String, Bytes) :- 35 | var(String), 36 | append(ByteString, [0], Bytes), 37 | chars_utf8bytes(String, ByteString). --------------------------------------------------------------------------------