New upstream snapshot.
Debian Janitor
2 years ago
0 | *.pyc | |
1 | docs/_build | |
2 | venv | |
3 | .venv/ | |
4 | .eggs | |
5 | .cache | |
6 | .tox | |
7 | .python-version | |
8 | anosql.egg-info | |
9 | .idea/ | |
10 | scratch/ |
0 | language: python | |
1 | python: | |
2 | - "2.7" | |
3 | - "3.5" | |
4 | services: | |
5 | - postgresql | |
6 | addons: | |
7 | postgresql: "10" | |
8 | apt: | |
9 | packages: | |
10 | - postgresql-10 | |
11 | - postgresql-client-10 | |
12 | - postgresql-server-dev-10 | |
13 | install: "pip install tox" | |
14 | script: tox |
0 | include README.md | |
0 | include README.rst | |
1 | include CHANGELOG | |
2 | include LICENSE | |
3 | include tox.ini | |
4 | include test_requirements.txt | |
5 | recursive-include docs *.rst Makefile conf.py make.bat | |
6 | recursive-include tests *.csv *.sql |
0 | Metadata-Version: 1.2 | |
1 | Name: anosql | |
2 | Version: 1.0.2 | |
3 | Summary: Easy SQL in Python | |
4 | Home-page: https://github.com/honza/anosql | |
5 | Author: Honza Pokorny | |
6 | Author-email: me@honza.ca | |
7 | Maintainer: Honza Pokorny | |
8 | Maintainer-email: me@honza.ca | |
9 | License: UNKNOWN | |
10 | Description: anosql | |
11 | ====== | |
12 | ||
13 | **NOTICE**: This project is now deprecated in favor of `aiosql`_. | |
14 | ||
15 | Unfortunately, I no longer have the time to devote to this project, and aiosql | |
16 | is now a lot more popular. I don't think it makes sense to maintain both. | |
17 | Open source ftw! Thanks for your hard work, `Will`_! | |
18 | ||
19 | .. _aiosql: https://github.com/nackjicholson/aiosql | |
20 | .. _Will: https://github.com/nackjicholson | |
21 | ||
22 | .. image:: https://badge.fury.io/py/anosql.svg | |
23 | :target: https://badge.fury.io/py/anosql | |
24 | :alt: pypi package version | |
25 | ||
26 | .. image:: http://readthedocs.org/projects/anosql/badge/?version=latest | |
27 | :target: http://anosql.readthedocs.io/en/latest/?badge=latest | |
28 | :alt: Documentation Status | |
29 | ||
30 | .. image:: https://travis-ci.org/honza/anosql.svg?branch=master | |
31 | :target: https://travis-ci.org/honza/anosql | |
32 | :alt: Travid build status | |
33 | ||
34 | A Python library for using SQL | |
35 | ||
36 | Inspired by the excellent `Yesql`_ library by Kris Jenkins. In my mother | |
37 | tongue, *ano* means *yes*. | |
38 | ||
39 | If you are on python3.6+ or need ``anosql`` to work with ``asyncio``-based database drivers, see the related project, `aiosql <https://github.com/nackjicholson/aiosql>`_. | |
40 | ||
41 | Complete documentation is available at `Read The Docs <https://anosql.readthedocs.io/en/latest/>`_. | |
42 | ||
43 | Installation | |
44 | ------------ | |
45 | ||
46 | :: | |
47 | ||
48 | $ pip install anosql | |
49 | ||
50 | Usage | |
51 | ----- | |
52 | ||
53 | Basics | |
54 | ****** | |
55 | ||
56 | Given a ``queries.sql`` file: | |
57 | ||
58 | .. code-block:: sql | |
59 | ||
60 | -- name: get-all-greetings | |
61 | -- Get all the greetings in the database | |
62 | SELECT * FROM greetings; | |
63 | ||
64 | -- name: select-users | |
65 | -- Get all the users from the database, | |
66 | -- and return it as a dict | |
67 | SELECT * FROM USERS; | |
68 | ||
69 | We can issue SQL queries, like so: | |
70 | ||
71 | .. code-block:: python | |
72 | ||
73 | import anosql | |
74 | import psycopg2 | |
75 | import sqlite3 | |
76 | ||
77 | # PostgreSQL | |
78 | conn = psycopg2.connect('...') | |
79 | queries = anosql.from_path('queries.sql', 'psycopg2') | |
80 | ||
81 | # Or, Sqlite3... | |
82 | conn = sqlite3.connect('cool.db') | |
83 | queries = anosql.from_path('queries.sql', 'sqlite3') | |
84 | ||
85 | queries.get_all_greetings(conn) | |
86 | # => [(1, 'en', 'Hi')] | |
87 | ||
88 | queries.get_all_greetings.__doc__ | |
89 | # => Get all the greetings in the database | |
90 | ||
91 | queries.get_all_greetings.sql | |
92 | # => SELECT * FROM greetings; | |
93 | ||
94 | queries.available_queries | |
95 | # => ['get_all_greetings'] | |
96 | ||
97 | ||
98 | Parameters | |
99 | ********** | |
100 | ||
101 | Often, you want to change parts of the query dynamically, particularly values in | |
102 | the ``WHERE`` clause. You can use parameters to do this: | |
103 | ||
104 | .. code-block:: sql | |
105 | ||
106 | -- name: get-greetings-for-language | |
107 | -- Get all the greetings in the database for given language | |
108 | SELECT * | |
109 | FROM greetings | |
110 | WHERE lang = %s; | |
111 | ||
112 | And they become positional parameters: | |
113 | ||
114 | .. code-block:: python | |
115 | ||
116 | visitor_language = "en" | |
117 | queries.get_greetings_for_language(conn, visitor_language) | |
118 | # => [(1, 'en', 'Hi')] | |
119 | ||
120 | ||
121 | One Row Query | |
122 | ************* | |
123 | ||
124 | Often, you would expect at most one row from a query, so that getting a list | |
125 | is not convenient. Appending ``?`` to the query name makes it return either one | |
126 | tuple if it returned one row, or ``None`` in other cases. | |
127 | ||
128 | .. code-block:: sql | |
129 | ||
130 | -- name: get-a-greeting? | |
131 | -- Get a greeting based on its id | |
132 | SELECT * | |
133 | FROM greetings | |
134 | WHERE id = %s; | |
135 | ||
136 | Then a tuple is returned: | |
137 | ||
138 | .. code-block:: python | |
139 | ||
140 | queries.get_a_greeting(conn, 1) | |
141 | # => (1, 'en', 'Hi') | |
142 | ||
143 | ||
144 | Named Parameters | |
145 | **************** | |
146 | ||
147 | To make queries with many parameters more understandable and maintainable, you | |
148 | can give the parameters names: | |
149 | ||
150 | .. code-block:: sql | |
151 | ||
152 | -- name: get-greetings-for-language-and-length | |
153 | -- Get all the greetings in the database for given language and length | |
154 | SELECT * | |
155 | FROM greetings | |
156 | WHERE lang = :lang | |
157 | AND len(greeting) <= :length_limit; | |
158 | ||
159 | If you were writing a Postgresql query, you could also format the parameters as | |
160 | ``%s(lang)`` and ``%s(length_limit)``. | |
161 | ||
162 | Then, call your queries like you would any Python function with named | |
163 | parameters: | |
164 | ||
165 | .. code-block:: python | |
166 | ||
167 | visitor_language = "en" | |
168 | ||
169 | greetings_for_texting = queries.get_greetings_for_language_and_length( | |
170 | conn, lang=visitor_language, length_limit=140) | |
171 | ||
172 | Update/Insert/Delete | |
173 | ******************** | |
174 | ||
175 | In order to run ``UPDATE``, ``INSERT``, or ``DELETE`` statements, you need to | |
176 | add ``!`` to the end of your query name. Anosql will then execute it properly. | |
177 | It will also return the number of affected rows. | |
178 | ||
179 | Insert queries returning autogenerated values | |
180 | ********************************************* | |
181 | ||
182 | If you want the auto-generated primary key to be returned after you run an | |
183 | insert query, you can add ``<!`` to the end of your query name. | |
184 | ||
185 | .. code-block:: sql | |
186 | ||
187 | -- name: create-user<! | |
188 | INSERT INTO person (name) VALUES (:name) | |
189 | ||
190 | Adding custom query loaders. | |
191 | **************************** | |
192 | ||
193 | Out of the box, ``anosql`` supports SQLite and PostgreSQL via the stdlib ``sqlite3`` database driver | |
194 | and ``psycopg2``. If you would like to extend ``anosql`` to communicate with other types of databases, | |
195 | you may create a driver adapter class and register it with ``anosql.core.register_driver_adapter()``. | |
196 | ||
197 | Driver adapters are duck-typed classes which adhere to the below interface. Looking at ``anosql/adapters`` package | |
198 | is a good place to get started by looking at how the ``psycopg2`` and ``sqlite3`` adapters work. | |
199 | ||
200 | To register a new loader:: | |
201 | ||
202 | import anosql | |
203 | import anosql.core | |
204 | ||
205 | class MyDbAdapter(): | |
206 | def process_sql(self, name, op_type, sql): | |
207 | pass | |
208 | ||
209 | def select(self, conn, sql, parameters): | |
210 | pass | |
211 | ||
212 | @contextmanager | |
213 | def select_cursor(self, conn, sql, parameters): | |
214 | pass | |
215 | ||
216 | def insert_update_delete(self, conn, sql, parameters): | |
217 | pass | |
218 | ||
219 | def insert_update_delete_many(self, conn, sql, parameters): | |
220 | pass | |
221 | ||
222 | def insert_returning(self, conn, sql, parameters): | |
223 | pass | |
224 | ||
225 | def execute_script(self, conn, sql): | |
226 | pass | |
227 | ||
228 | ||
229 | anosql.core.register_driver_adapter("mydb", MyDbAdapter) | |
230 | ||
231 | # To use make a connection to your db, and pass "mydb" as the db_type: | |
232 | import mydbdriver | |
233 | conn = mydbriver.connect("...") | |
234 | ||
235 | anosql.load_queries("path/to/sql/", "mydb") | |
236 | greetings = anosql.get_greetings(conn) | |
237 | ||
238 | conn.close() | |
239 | ||
240 | If your adapter constructor takes arguments, you can register a function which can build | |
241 | your adapter instance:: | |
242 | ||
243 | def adapter_factory(): | |
244 | return MyDbAdapter("foo", 42) | |
245 | ||
246 | anosql.register_driver_adapter("mydb", adapter_factory) | |
247 | ||
248 | Tests | |
249 | ----- | |
250 | ||
251 | :: | |
252 | ||
253 | $ pip install tox | |
254 | $ tox | |
255 | ||
256 | License | |
257 | ------- | |
258 | ||
259 | BSD, short and sweet | |
260 | ||
261 | .. _Yesql: https://github.com/krisajenkins/yesql/ | |
262 | ||
263 | Platform: UNKNOWN |
0 | 0 | anosql |
1 | 1 | ====== |
2 | 2 | |
3 | **NOTICE**: This project is now deprecated in favor of `aiosql`_. | |
4 | ||
5 | Unfortunately, I no longer have the time to devote to this project, and aiosql | |
6 | is now a lot more popular. I don't think it makes sense to maintain both. | |
7 | Open source ftw! Thanks for your hard work, `Will`_! | |
8 | ||
9 | .. _aiosql: https://github.com/nackjicholson/aiosql | |
10 | .. _Will: https://github.com/nackjicholson | |
11 | ||
3 | 12 | .. image:: https://badge.fury.io/py/anosql.svg |
4 | 13 | :target: https://badge.fury.io/py/anosql |
14 | :alt: pypi package version | |
5 | 15 | |
6 | 16 | .. image:: http://readthedocs.org/projects/anosql/badge/?version=latest |
7 | 17 | :target: http://anosql.readthedocs.io/en/latest/?badge=latest |
9 | 19 | |
10 | 20 | .. image:: https://travis-ci.org/honza/anosql.svg?branch=master |
11 | 21 | :target: https://travis-ci.org/honza/anosql |
22 | :alt: Travid build status | |
12 | 23 | |
13 | 24 | A Python library for using SQL |
14 | 25 | |
15 | 26 | Inspired by the excellent `Yesql`_ library by Kris Jenkins. In my mother |
16 | 27 | tongue, *ano* means *yes*. |
17 | 28 | |
18 | If you are on python3.6+ or need ``anosql`` to work with ``asyncio`` based database drivers. | |
19 | See the related project `aiosql <https://github.com/nackjicholson/aiosql>`_. | |
29 | If you are on python3.6+ or need ``anosql`` to work with ``asyncio``-based database drivers, see the related project, `aiosql <https://github.com/nackjicholson/aiosql>`_. | |
30 | ||
31 | Complete documentation is available at `Read The Docs <https://anosql.readthedocs.io/en/latest/>`_. | |
20 | 32 | |
21 | 33 | Installation |
22 | 34 | ------------ |
39 | 51 | -- Get all the greetings in the database |
40 | 52 | SELECT * FROM greetings; |
41 | 53 | |
42 | -- name: $select-users | |
54 | -- name: select-users | |
43 | 55 | -- Get all the users from the database, |
44 | 56 | -- and return it as a dict |
45 | 57 | SELECT * FROM USERS; |
58 | 70 | |
59 | 71 | # Or, Sqlite3... |
60 | 72 | conn = sqlite3.connect('cool.db') |
61 | queries = anosql.from_path('queries.sql', 'sqlite3) | |
73 | queries = anosql.from_path('queries.sql', 'sqlite3') | |
62 | 74 | |
63 | 75 | queries.get_all_greetings(conn) |
64 | # => [(1, 'Hi')] | |
76 | # => [(1, 'en', 'Hi')] | |
65 | 77 | |
66 | 78 | queries.get_all_greetings.__doc__ |
67 | 79 | # => Get all the greetings in the database |
81 | 93 | |
82 | 94 | .. code-block:: sql |
83 | 95 | |
84 | -- name: get-greetings-for-language-and-length | |
85 | -- Get all the greetings in the database | |
96 | -- name: get-greetings-for-language | |
97 | -- Get all the greetings in the database for given language | |
86 | 98 | SELECT * |
87 | 99 | FROM greetings |
88 | 100 | WHERE lang = %s; |
92 | 104 | .. code-block:: python |
93 | 105 | |
94 | 106 | visitor_language = "en" |
95 | queries.get_all_greetings(conn, visitor_language) | |
96 | ||
107 | queries.get_greetings_for_language(conn, visitor_language) | |
108 | # => [(1, 'en', 'Hi')] | |
109 | ||
110 | ||
111 | One Row Query | |
112 | ************* | |
113 | ||
114 | Often, you would expect at most one row from a query, so that getting a list | |
115 | is not convenient. Appending ``?`` to the query name makes it return either one | |
116 | tuple if it returned one row, or ``None`` in other cases. | |
117 | ||
118 | .. code-block:: sql | |
119 | ||
120 | -- name: get-a-greeting? | |
121 | -- Get a greeting based on its id | |
122 | SELECT * | |
123 | FROM greetings | |
124 | WHERE id = %s; | |
125 | ||
126 | Then a tuple is returned: | |
127 | ||
128 | .. code-block:: python | |
129 | ||
130 | queries.get_a_greeting(conn, 1) | |
131 | # => (1, 'en', 'Hi') | |
97 | 132 | |
98 | 133 | |
99 | 134 | Named Parameters |
105 | 140 | .. code-block:: sql |
106 | 141 | |
107 | 142 | -- name: get-greetings-for-language-and-length |
108 | -- Get all the greetings in the database | |
143 | -- Get all the greetings in the database for given language and length | |
109 | 144 | SELECT * |
110 | 145 | FROM greetings |
111 | 146 | WHERE lang = :lang |
121 | 156 | |
122 | 157 | visitor_language = "en" |
123 | 158 | |
124 | greetings_for_texting = queries.get_all_greetings( | |
159 | greetings_for_texting = queries.get_greetings_for_language_and_length( | |
125 | 160 | conn, lang=visitor_language, length_limit=140) |
126 | 161 | |
127 | 162 | Update/Insert/Delete |
145 | 180 | Adding custom query loaders. |
146 | 181 | **************************** |
147 | 182 | |
148 | Out of the box ``anosql`` supports SQLite and PostgreSQL via the stdlib ``sqlite3`` database driver | |
149 | and ``psycopg2``. If you would like to extend ``anosql`` to communicate with another type of databases | |
150 | you may create a driver adapeter class and register it with ``anosql.register_driver_adapter()``. | |
183 | Out of the box, ``anosql`` supports SQLite and PostgreSQL via the stdlib ``sqlite3`` database driver | |
184 | and ``psycopg2``. If you would like to extend ``anosql`` to communicate with other types of databases, | |
185 | you may create a driver adapter class and register it with ``anosql.core.register_driver_adapter()``. | |
151 | 186 | |
152 | 187 | Driver adapters are duck-typed classes which adhere to the below interface. Looking at ``anosql/adapters`` package |
153 | 188 | is a good place to get started by looking at how the ``psycopg2`` and ``sqlite3`` adapters work. |
155 | 190 | To register a new loader:: |
156 | 191 | |
157 | 192 | import anosql |
193 | import anosql.core | |
158 | 194 | |
159 | 195 | class MyDbAdapter(): |
160 | 196 | def process_sql(self, name, op_type, sql): |
180 | 216 | pass |
181 | 217 | |
182 | 218 | |
183 | anosql.register_driver_adapter("mydb", MyDbAdapter) | |
219 | anosql.core.register_driver_adapter("mydb", MyDbAdapter) | |
184 | 220 | |
185 | 221 | # To use make a connection to your db, and pass "mydb" as the db_type: |
186 | 222 | import mydbdriver |
191 | 227 | |
192 | 228 | conn.close() |
193 | 229 | |
194 | If your adapter constructor takes arguments you can register a function which can build | |
230 | If your adapter constructor takes arguments, you can register a function which can build | |
195 | 231 | your adapter instance:: |
196 | 232 | |
197 | 233 | def adapter_factory(): |
0 | from anosql.core import from_path, from_str, SQLOperationType | |
1 | from anosql.exceptions import SQLLoadException, SQLParseException | |
0 | from .core import from_path, from_str, SQLOperationType | |
1 | from .exceptions import SQLLoadException, SQLParseException | |
2 | 2 | |
3 | 3 | __all__ = ["from_path", "from_str", "SQLOperationType", "SQLLoadException", "SQLParseException"] |
4 |
0 | 0 | from contextlib import contextmanager |
1 | 1 | |
2 | from anosql.patterns import var_pattern | |
2 | from ..patterns import var_pattern | |
3 | 3 | |
4 | 4 | |
5 | 5 | def replacer(match): |
40 | 40 | cur.execute(sql, parameters) |
41 | 41 | |
42 | 42 | @staticmethod |
43 | def insert_update_delete_many(conn, _query_name, sql, parmeters): | |
43 | def insert_update_delete_many(conn, _query_name, sql, parameters): | |
44 | 44 | with conn.cursor() as cur: |
45 | cur.executemany(sql, parmeters) | |
45 | cur.executemany(sql, parameters) | |
46 | 46 | |
47 | 47 | @staticmethod |
48 | 48 | def insert_returning(conn, _query_name, sql, parameters): |
0 | 0 | import os |
1 | 1 | |
2 | from anosql.adapters.psycopg2 import PsycoPG2Adapter | |
3 | from anosql.adapters.sqlite3 import SQLite3DriverAdapter | |
4 | from anosql.exceptions import SQLLoadException, SQLParseException | |
5 | from anosql.patterns import ( | |
2 | from .adapters.psycopg2 import PsycoPG2Adapter | |
3 | from .adapters.sqlite3 import SQLite3DriverAdapter | |
4 | from .exceptions import SQLLoadException, SQLParseException | |
5 | from .patterns import ( | |
6 | 6 | query_name_definition_pattern, |
7 | 7 | empty_pattern, |
8 | 8 | doc_comment_pattern, |
95 | 95 | INSERT_UPDATE_DELETE_MANY = 2 |
96 | 96 | SCRIPT = 3 |
97 | 97 | SELECT = 4 |
98 | SELECT_ONE_ROW = 5 | |
98 | 99 | |
99 | 100 | |
100 | 101 | class Queries: |
171 | 172 | return driver_adapter.insert_update_delete_many(conn, query_name, sql, *parameters) |
172 | 173 | elif op_type == SQLOperationType.SCRIPT: |
173 | 174 | return driver_adapter.execute_script(conn, sql) |
175 | elif op_type == SQLOperationType.SELECT_ONE_ROW: | |
176 | res = driver_adapter.select(conn, query_name, sql, parameters) | |
177 | return res[0] if len(res) == 1 else None | |
174 | 178 | elif op_type == SQLOperationType.SELECT: |
175 | 179 | return driver_adapter.select(conn, query_name, sql, parameters) |
176 | 180 | else: |
211 | 215 | query_name = query_name[:-1] |
212 | 216 | elif query_name.endswith("#"): |
213 | 217 | op_type = SQLOperationType.SCRIPT |
218 | query_name = query_name[:-1] | |
219 | elif query_name.endswith("?"): | |
220 | op_type = SQLOperationType.SELECT_ONE_ROW | |
214 | 221 | query_name = query_name[:-1] |
215 | 222 | else: |
216 | 223 | op_type = SQLOperationType.SELECT |
22 | 22 | var_pattern = re.compile( |
23 | 23 | r'(?P<dblquote>"[^"]+")|' |
24 | 24 | r"(?P<quote>\'[^\']+\')|" |
25 | r"(?P<lead>[^:]):(?P<var_name>[\w-]+)(?P<trail>[^:])" | |
25 | r"(?P<lead>[^:]):(?P<var_name>[\w-]+)(?P<trail>[^:]?)" | |
26 | 26 | ) |
27 | 27 | """ |
28 | 28 | Pattern: Identifies variable definitions in SQL code. |
0 | Metadata-Version: 1.2 | |
1 | Name: anosql | |
2 | Version: 1.0.2 | |
3 | Summary: Easy SQL in Python | |
4 | Home-page: https://github.com/honza/anosql | |
5 | Author: Honza Pokorny | |
6 | Author-email: me@honza.ca | |
7 | Maintainer: Honza Pokorny | |
8 | Maintainer-email: me@honza.ca | |
9 | License: UNKNOWN | |
10 | Description: anosql | |
11 | ====== | |
12 | ||
13 | **NOTICE**: This project is now deprecated in favor of `aiosql`_. | |
14 | ||
15 | Unfortunately, I no longer have the time to devote to this project, and aiosql | |
16 | is now a lot more popular. I don't think it makes sense to maintain both. | |
17 | Open source ftw! Thanks for your hard work, `Will`_! | |
18 | ||
19 | .. _aiosql: https://github.com/nackjicholson/aiosql | |
20 | .. _Will: https://github.com/nackjicholson | |
21 | ||
22 | .. image:: https://badge.fury.io/py/anosql.svg | |
23 | :target: https://badge.fury.io/py/anosql | |
24 | :alt: pypi package version | |
25 | ||
26 | .. image:: http://readthedocs.org/projects/anosql/badge/?version=latest | |
27 | :target: http://anosql.readthedocs.io/en/latest/?badge=latest | |
28 | :alt: Documentation Status | |
29 | ||
30 | .. image:: https://travis-ci.org/honza/anosql.svg?branch=master | |
31 | :target: https://travis-ci.org/honza/anosql | |
32 | :alt: Travid build status | |
33 | ||
34 | A Python library for using SQL | |
35 | ||
36 | Inspired by the excellent `Yesql`_ library by Kris Jenkins. In my mother | |
37 | tongue, *ano* means *yes*. | |
38 | ||
39 | If you are on python3.6+ or need ``anosql`` to work with ``asyncio``-based database drivers, see the related project, `aiosql <https://github.com/nackjicholson/aiosql>`_. | |
40 | ||
41 | Complete documentation is available at `Read The Docs <https://anosql.readthedocs.io/en/latest/>`_. | |
42 | ||
43 | Installation | |
44 | ------------ | |
45 | ||
46 | :: | |
47 | ||
48 | $ pip install anosql | |
49 | ||
50 | Usage | |
51 | ----- | |
52 | ||
53 | Basics | |
54 | ****** | |
55 | ||
56 | Given a ``queries.sql`` file: | |
57 | ||
58 | .. code-block:: sql | |
59 | ||
60 | -- name: get-all-greetings | |
61 | -- Get all the greetings in the database | |
62 | SELECT * FROM greetings; | |
63 | ||
64 | -- name: select-users | |
65 | -- Get all the users from the database, | |
66 | -- and return it as a dict | |
67 | SELECT * FROM USERS; | |
68 | ||
69 | We can issue SQL queries, like so: | |
70 | ||
71 | .. code-block:: python | |
72 | ||
73 | import anosql | |
74 | import psycopg2 | |
75 | import sqlite3 | |
76 | ||
77 | # PostgreSQL | |
78 | conn = psycopg2.connect('...') | |
79 | queries = anosql.from_path('queries.sql', 'psycopg2') | |
80 | ||
81 | # Or, Sqlite3... | |
82 | conn = sqlite3.connect('cool.db') | |
83 | queries = anosql.from_path('queries.sql', 'sqlite3') | |
84 | ||
85 | queries.get_all_greetings(conn) | |
86 | # => [(1, 'en', 'Hi')] | |
87 | ||
88 | queries.get_all_greetings.__doc__ | |
89 | # => Get all the greetings in the database | |
90 | ||
91 | queries.get_all_greetings.sql | |
92 | # => SELECT * FROM greetings; | |
93 | ||
94 | queries.available_queries | |
95 | # => ['get_all_greetings'] | |
96 | ||
97 | ||
98 | Parameters | |
99 | ********** | |
100 | ||
101 | Often, you want to change parts of the query dynamically, particularly values in | |
102 | the ``WHERE`` clause. You can use parameters to do this: | |
103 | ||
104 | .. code-block:: sql | |
105 | ||
106 | -- name: get-greetings-for-language | |
107 | -- Get all the greetings in the database for given language | |
108 | SELECT * | |
109 | FROM greetings | |
110 | WHERE lang = %s; | |
111 | ||
112 | And they become positional parameters: | |
113 | ||
114 | .. code-block:: python | |
115 | ||
116 | visitor_language = "en" | |
117 | queries.get_greetings_for_language(conn, visitor_language) | |
118 | # => [(1, 'en', 'Hi')] | |
119 | ||
120 | ||
121 | One Row Query | |
122 | ************* | |
123 | ||
124 | Often, you would expect at most one row from a query, so that getting a list | |
125 | is not convenient. Appending ``?`` to the query name makes it return either one | |
126 | tuple if it returned one row, or ``None`` in other cases. | |
127 | ||
128 | .. code-block:: sql | |
129 | ||
130 | -- name: get-a-greeting? | |
131 | -- Get a greeting based on its id | |
132 | SELECT * | |
133 | FROM greetings | |
134 | WHERE id = %s; | |
135 | ||
136 | Then a tuple is returned: | |
137 | ||
138 | .. code-block:: python | |
139 | ||
140 | queries.get_a_greeting(conn, 1) | |
141 | # => (1, 'en', 'Hi') | |
142 | ||
143 | ||
144 | Named Parameters | |
145 | **************** | |
146 | ||
147 | To make queries with many parameters more understandable and maintainable, you | |
148 | can give the parameters names: | |
149 | ||
150 | .. code-block:: sql | |
151 | ||
152 | -- name: get-greetings-for-language-and-length | |
153 | -- Get all the greetings in the database for given language and length | |
154 | SELECT * | |
155 | FROM greetings | |
156 | WHERE lang = :lang | |
157 | AND len(greeting) <= :length_limit; | |
158 | ||
159 | If you were writing a Postgresql query, you could also format the parameters as | |
160 | ``%s(lang)`` and ``%s(length_limit)``. | |
161 | ||
162 | Then, call your queries like you would any Python function with named | |
163 | parameters: | |
164 | ||
165 | .. code-block:: python | |
166 | ||
167 | visitor_language = "en" | |
168 | ||
169 | greetings_for_texting = queries.get_greetings_for_language_and_length( | |
170 | conn, lang=visitor_language, length_limit=140) | |
171 | ||
172 | Update/Insert/Delete | |
173 | ******************** | |
174 | ||
175 | In order to run ``UPDATE``, ``INSERT``, or ``DELETE`` statements, you need to | |
176 | add ``!`` to the end of your query name. Anosql will then execute it properly. | |
177 | It will also return the number of affected rows. | |
178 | ||
179 | Insert queries returning autogenerated values | |
180 | ********************************************* | |
181 | ||
182 | If you want the auto-generated primary key to be returned after you run an | |
183 | insert query, you can add ``<!`` to the end of your query name. | |
184 | ||
185 | .. code-block:: sql | |
186 | ||
187 | -- name: create-user<! | |
188 | INSERT INTO person (name) VALUES (:name) | |
189 | ||
190 | Adding custom query loaders. | |
191 | **************************** | |
192 | ||
193 | Out of the box, ``anosql`` supports SQLite and PostgreSQL via the stdlib ``sqlite3`` database driver | |
194 | and ``psycopg2``. If you would like to extend ``anosql`` to communicate with other types of databases, | |
195 | you may create a driver adapter class and register it with ``anosql.core.register_driver_adapter()``. | |
196 | ||
197 | Driver adapters are duck-typed classes which adhere to the below interface. Looking at ``anosql/adapters`` package | |
198 | is a good place to get started by looking at how the ``psycopg2`` and ``sqlite3`` adapters work. | |
199 | ||
200 | To register a new loader:: | |
201 | ||
202 | import anosql | |
203 | import anosql.core | |
204 | ||
205 | class MyDbAdapter(): | |
206 | def process_sql(self, name, op_type, sql): | |
207 | pass | |
208 | ||
209 | def select(self, conn, sql, parameters): | |
210 | pass | |
211 | ||
212 | @contextmanager | |
213 | def select_cursor(self, conn, sql, parameters): | |
214 | pass | |
215 | ||
216 | def insert_update_delete(self, conn, sql, parameters): | |
217 | pass | |
218 | ||
219 | def insert_update_delete_many(self, conn, sql, parameters): | |
220 | pass | |
221 | ||
222 | def insert_returning(self, conn, sql, parameters): | |
223 | pass | |
224 | ||
225 | def execute_script(self, conn, sql): | |
226 | pass | |
227 | ||
228 | ||
229 | anosql.core.register_driver_adapter("mydb", MyDbAdapter) | |
230 | ||
231 | # To use make a connection to your db, and pass "mydb" as the db_type: | |
232 | import mydbdriver | |
233 | conn = mydbriver.connect("...") | |
234 | ||
235 | anosql.load_queries("path/to/sql/", "mydb") | |
236 | greetings = anosql.get_greetings(conn) | |
237 | ||
238 | conn.close() | |
239 | ||
240 | If your adapter constructor takes arguments, you can register a function which can build | |
241 | your adapter instance:: | |
242 | ||
243 | def adapter_factory(): | |
244 | return MyDbAdapter("foo", 42) | |
245 | ||
246 | anosql.register_driver_adapter("mydb", adapter_factory) | |
247 | ||
248 | Tests | |
249 | ----- | |
250 | ||
251 | :: | |
252 | ||
253 | $ pip install tox | |
254 | $ tox | |
255 | ||
256 | License | |
257 | ------- | |
258 | ||
259 | BSD, short and sweet | |
260 | ||
261 | .. _Yesql: https://github.com/krisajenkins/yesql/ | |
262 | ||
263 | Platform: UNKNOWN |
0 | CHANGELOG | |
1 | LICENSE | |
2 | MANIFEST.in | |
3 | README.rst | |
4 | setup.cfg | |
5 | setup.py | |
6 | test_requirements.txt | |
7 | tox.ini | |
8 | anosql/__init__.py | |
9 | anosql/core.py | |
10 | anosql/exceptions.py | |
11 | anosql/patterns.py | |
12 | anosql.egg-info/PKG-INFO | |
13 | anosql.egg-info/SOURCES.txt | |
14 | anosql.egg-info/dependency_links.txt | |
15 | anosql.egg-info/top_level.txt | |
16 | anosql/adapters/__init__.py | |
17 | anosql/adapters/psycopg2.py | |
18 | anosql/adapters/sqlite3.py | |
19 | docs/Makefile | |
20 | docs/conf.py | |
21 | docs/defining_queries.rst | |
22 | docs/extending.rst | |
23 | docs/getting_started.rst | |
24 | docs/index.rst | |
25 | docs/make.bat | |
26 | docs/upgrading.rst | |
27 | docs/source/anosql.adapters.psycopg2.rst | |
28 | docs/source/anosql.adapters.rst | |
29 | docs/source/anosql.adapters.sqlite3.rst | |
30 | docs/source/anosql.core.rst | |
31 | docs/source/anosql.exceptions.rst | |
32 | docs/source/anosql.patterns.rst | |
33 | docs/source/anosql.rst | |
34 | docs/source/modules.rst | |
35 | tests/__init__.py | |
36 | tests/conftest.py | |
37 | tests/test_psycopg2.py | |
38 | tests/test_simple.py | |
39 | tests/test_sqlite3.py | |
40 | tests/blogdb/data/blogs_data.csv | |
41 | tests/blogdb/data/users_data.csv | |
42 | tests/blogdb/sql/blogs/blogs.sql | |
43 | tests/blogdb/sql/blogs/blogs_pg.sql | |
44 | tests/blogdb/sql/blogs/blogs_sqlite.sql | |
45 | tests/blogdb/sql/users/users.sql⏎ |
0 | anosql (1.0.1-2) UNRELEASED; urgency=medium | |
0 | anosql (1.0.2+git20200909.1.903d82f-1) UNRELEASED; urgency=medium | |
1 | 1 | |
2 | 2 | [ Ondřej Nový ] |
3 | 3 | * Bump Standards-Version to 4.4.1. |
10 | 10 | * Set upstream metadata fields: Bug-Database, Bug-Submit, Repository, |
11 | 11 | Repository-Browse. |
12 | 12 | * Update standards version to 4.5.0, no changes needed. |
13 | * New upstream snapshot. | |
13 | 14 | |
14 | -- Ondřej Nový <onovy@debian.org> Fri, 18 Oct 2019 15:27:26 +0200 | |
15 | -- Ondřej Nový <onovy@debian.org> Thu, 22 Jul 2021 11:00:15 -0000 | |
15 | 16 | |
16 | 17 | anosql (1.0.1-1) unstable; urgency=medium |
17 | 18 |
18 | 18 | # import os |
19 | 19 | # import sys |
20 | 20 | # sys.path.insert(0, os.path.abspath('.')) |
21 | import pkg_resources | |
21 | 22 | |
22 | 23 | # -- General configuration ------------------------------------------------ |
23 | 24 | |
56 | 57 | # built documents. |
57 | 58 | # |
58 | 59 | # The short X.Y version. |
59 | version = u'1.0.0' | |
60 | version = pkg_resources.get_distribution('anosql').version | |
60 | 61 | # The full version, including alpha/beta/rc tags. |
61 | release = u'1.0.0' | |
62 | release = version | |
62 | 63 | |
63 | 64 | # The language for content autogenerated by Sphinx. Refer to documentation |
64 | 65 | # for a list of supported languages. |
152 | 153 | # Add any paths that contain custom static files (such as style sheets) here, |
153 | 154 | # relative to this directory. They are copied after the builtin static files, |
154 | 155 | # so a file named "default.css" will overwrite the builtin "default.css". |
155 | html_static_path = ['_static'] | |
156 | html_static_path = [] | |
156 | 157 | |
157 | 158 | # Add any extra paths that contain custom files (such as robots.txt or |
158 | 159 | # .htaccess) here, relative to this directory. These files are copied |
5 | 5 | ====================== |
6 | 6 | |
7 | 7 | Name definitions are how ``anosql`` determines how to name the SQL code blocks which are loaded. |
8 | A query name definition is a normal SQL comment starting with "-- name:" and is followed by the | |
9 | name of the query. You can use ``-`` or ``_`` in your query names, but the methods in python | |
10 | will always be valid python names using underscores. | |
8 | A query name definition is a normal SQL comment starting with "\-\- name:" and is followed by the | |
9 | name of the query. You can use ``-`` or ``_`` in your query names, but the methods in Python | |
10 | will always be valid Python names using underscores. | |
11 | 11 | |
12 | 12 | .. code-block:: sql |
13 | 13 | |
17 | 17 | The above example when loaded by ``anosql.from_path`` will return an object with a |
18 | 18 | ``.get_all_blogs(conn)`` method. |
19 | 19 | |
20 | Your SQL comments will be added to your methods as python documentation, and accessible by calling | |
20 | Your SQL comments will be added to your methods as Python docstrings, and accessible by calling | |
21 | 21 | ``help()`` on them. |
22 | 22 | |
23 | 23 | .. code-block:: sql |
32 | 32 | queries = anosql.from_path("blogs.sql", "sqlite3") |
33 | 33 | help(anosql.get_all_blogs) |
34 | 34 | |
35 | output | |
35 | returns | |
36 | 36 | |
37 | 37 | .. code-block:: text |
38 | 38 | |
51 | 51 | characters trailing it. This lack of operator is actually the most basic operator which performs |
52 | 52 | SQL ``select`` statements and returns a list of rows. When writing an application you will often |
53 | 53 | need to perform other operations besides selects, like inserts, deletes, and bulk opearations. The |
54 | operators detailed in this section let you declare in your SQL, how your code should be executed | |
54 | operators detailed in this section let you declare in your SQL how your code should be executed | |
55 | 55 | by the database driver. |
56 | 56 | |
57 | 57 | Insert/Update/Delete with ``!`` |
141 | 141 | :published |
142 | 142 | ) |
143 | 143 | |
144 | Applying this to a list of blogs in python:: | |
144 | Applying this to a list of blogs in Python:: | |
145 | 145 | |
146 | 146 | queries = anosql.from_path("blogs.sql", "psycopg2") |
147 | 147 | blogs = [ |
154 | 154 | Execute SQL script statements with ``#`` |
155 | 155 | --------------------------------------------- |
156 | 156 | |
157 | Executes some sql statements as a script. These methods don't do variable substitution, or return | |
158 | any rows. An example usecase is using data definition statements like create table in order to | |
157 | Executes some SQL statements as a script. These methods don't do variable substitution, or return | |
158 | any rows. An example use case is using data definition statements like `create` table in order to | |
159 | 159 | setup your database. |
160 | 160 | |
161 | 161 | .. code-block:: sql |
3 | 3 | Extending anosql |
4 | 4 | ################ |
5 | 5 | |
6 | .. _driver-adapters: | |
7 | ||
6 | 8 | Driver Adapters |
7 | 9 | --------------- |
8 | 10 | |
9 | Database driver adapters in ``anosql`` are a duck-typed class which follow the below interface.:: | |
11 | Database driver adapters in ``anosql`` are duck-typed classes which follow the below interface.:: | |
10 | 12 | |
11 | 13 | class MyDbAdapter(): |
12 | 14 | def process_sql(self, name, op_type, sql): |
32 | 34 | pass |
33 | 35 | |
34 | 36 | |
35 | anosql.register_driver_adapter("mydb", MyDbAdapter) | |
37 | anosql.core.register_driver_adapter("mydb", MyDbAdapter) | |
36 | 38 | |
37 | 39 | If your adapter constructor takes arguments you can register a function which can build |
38 | 40 | your adapter instance:: |
40 | 42 | def adapter_factory(): |
41 | 43 | return MyDbAdapter("foo", 42) |
42 | 44 | |
43 | anosql.register_driver_adapter("mydb", adapter_factory) | |
45 | anosql.core.register_driver_adapter("mydb", adapter_factory) | |
44 | 46 | |
45 | 47 | Looking at the source of the builtin |
46 | 48 | `adapters/ <https://github.com/honza/anosql/tree/master/anosql/adapters>`_ is a great place |
23 | 23 | from worlds |
24 | 24 | where world_name = :world_name; |
25 | 25 | |
26 | By specifying ``db_driver="sqlite3"`` we can use the python stdlib ``sqlite3`` driver to execute these sql queries and | |
26 | By specifying ``db_driver="sqlite3"`` we can use the Python stdlib ``sqlite3`` driver to execute these SQL queries and | |
27 | 27 | get the results. We're also using the ``sqlite3.Row`` type for our records to make it easy to access our data via |
28 | 28 | their column names rather than as tuple indices. |
29 | 29 |
7 | 7 | |
8 | 8 | .. image:: https://badge.fury.io/py/anosql.svg |
9 | 9 | :target: https://badge.fury.io/py/anosql |
10 | :alt: pypi package version | |
10 | 11 | |
11 | 12 | .. image:: http://readthedocs.org/projects/anosql/badge/?version=latest |
12 | 13 | :target: http://anosql.readthedocs.io/en/latest/?badge=latest |
14 | :alt: Documentation status | |
13 | 15 | |
14 | 16 | .. image:: https://travis-ci.org/honza/anosql.svg?branch=master |
15 | 17 | :target: https://travis-ci.org/honza/anosql |
18 | :alt: Travis build status | |
16 | 19 | |
17 | 20 | A Python library for using SQL |
18 | 21 | |
19 | 22 | Inspired by the excellent `Yesql`_ library by Kris Jenkins. In my mother |
20 | 23 | tongue, *ano* means *yes*. |
21 | 24 | |
22 | If you are on python3.6+ or need ``anosql`` to work with ``asyncio`` based database drivers. | |
23 | See the related project `aiosql <https://github.com/nackjicholson/aiosql>`_. | |
25 | If you are on python3.6+ or need ``anosql`` to work with ``asyncio`` based database drivers, see the related project `aiosql <https://github.com/nackjicholson/aiosql>`_. | |
24 | 26 | |
25 | 27 | Installation |
26 | 28 | ------------ |
57 | 59 | |
58 | 60 | # Or, Sqlite3... |
59 | 61 | conn = sqlite3.connect('cool.db') |
60 | queries = anosql.from_path('queries.sql', 'sqlite3) | |
62 | queries = anosql.from_path('queries.sql', 'sqlite3') | |
61 | 63 | |
62 | 64 | queries.get_all_greetings(conn) |
63 | 65 | # => [(1, 'Hi')] |
75 | 77 | Parameters |
76 | 78 | ********** |
77 | 79 | |
78 | Often, you want to change parts of the query dynamically, particularly values in the WHERE clause. | |
80 | Often, you want to change parts of the query dynamically, particularly values in the ``WHERE`` clause. | |
79 | 81 | You can use parameters to do this: |
80 | 82 | |
81 | 83 | .. code-block:: sql |
82 | 84 | |
83 | -- name: get-greetings-for-language-and-length | |
84 | -- Get all the greetings in the database | |
85 | -- name: get-greetings-for-language | |
86 | -- Get all the greetings in the database for a given language | |
85 | 87 | SELECT * |
86 | 88 | FROM greetings |
87 | 89 | WHERE lang = %s; |
91 | 93 | .. code-block:: python |
92 | 94 | |
93 | 95 | visitor_language = "en" |
94 | queries.get_all_greetings(conn, visitor_language) | |
96 | queries.get_all_greetings_for_language(conn, visitor_language) | |
95 | 97 | |
96 | 98 | |
97 | 99 | |
102 | 104 | |
103 | 105 | .. code-block:: sql |
104 | 106 | |
105 | -- name: get-greetings-for-language-and-length | |
106 | -- Get all the greetings in the database | |
107 | -- name: get-greetings-for-language | |
108 | -- Get all the greetings in the database for given language and length | |
107 | 109 | SELECT * |
108 | 110 | FROM greetings |
109 | 111 | WHERE lang = :lang |
4 | 4 | |
5 | 5 | setup( |
6 | 6 | name='anosql', |
7 | version='1.0.1', | |
7 | version='1.0.2', | |
8 | 8 | url='https://github.com/honza/anosql', |
9 | 9 | install_requires=[], |
10 | 10 | description='Easy SQL in Python', |
4 | 4 | -- name: get-all-sorted |
5 | 5 | -- Get all user records sorted by username |
6 | 6 | select * from users order by username asc; |
7 | ||
8 | -- name: get-one? | |
9 | -- Get one user based on its id | |
10 | select username, firstname, lastname from users where userid = %s; |
19 | 19 | firstname integer not null, |
20 | 20 | lastname text not null |
21 | 21 | ); |
22 | ||
22 | ||
23 | 23 | create table blogs ( |
24 | 24 | blogid integer not null primary key, |
25 | 25 | userid integer not null, |
73 | 73 | assert q.get_all_values(sqlite) == [(10, 11, 12)] |
74 | 74 | |
75 | 75 | |
76 | def test_one_row(sqlite): | |
77 | _test_one_row = ("-- name: one-row?\n" | |
78 | "SELECT 1, 'hello';\n\n" | |
79 | "-- name: two-rows?\n" | |
80 | "SELECT 1 UNION SELECT 2;\n") | |
81 | q = anosql.from_str(_test_one_row, "sqlite3") | |
82 | assert q.one_row(sqlite) == (1, 'hello') | |
83 | assert q.two_rows(sqlite) is None | |
84 | ||
85 | ||
76 | 86 | def test_simple_query_pg(postgresql): |
77 | 87 | _queries = ("-- name: create-some-table#\n" |
78 | 88 | "-- testing insertion\n" |
192 | 202 | q.insert_some_value(postgresql) |
193 | 203 | |
194 | 204 | assert q.get_all_values(postgresql, a=1) == [(1, 2, 3)] |
205 | ||
206 | ||
207 | def test_without_trailing_semi_colon_pg(): | |
208 | """Make sure keywords ending queries are recognized even without | |
209 | semi-colons. | |
210 | """ | |
211 | _queries = ("-- name: get-by-a\n" | |
212 | "SELECT a, b, c FROM foo WHERE a = :a\n") | |
213 | q = anosql.from_str(_queries, "psycopg2") | |
214 | assert q.get_by_a.sql == "SELECT a, b, c FROM foo WHERE a = %(a)s" |
0 | 0 | [tox] |
1 | envlist = py27, py35 | |
1 | envlist = py27, py35, py37, flake8, docs, check-manifest | |
2 | 2 | skip_missing_interpreters = True |
3 | 3 | |
4 | 4 | [testenv] |
5 | 5 | deps = -rtest_requirements.txt |
6 | commands = py.test tests | |
6 | commands = {envpython} -m pytest {posargs:tests} | |
7 | ||
8 | [testenv:flake8] | |
9 | skip_install = true | |
10 | deps = flake8 | |
11 | commands = {envpython} -m flake8 {posargs} | |
12 | ||
13 | [flake8] | |
14 | max-line-length=100 | |
15 | ||
16 | [testenv:docs] | |
17 | deps = | |
18 | sphinx | |
19 | alabaster | |
20 | commands = {envpython} -m sphinx.cmd.build -W -b html docs docs/_build/html | |
21 | ||
22 | [testenv:check-manifest] | |
23 | skip_install = true | |
24 | deps = | |
25 | check-manifest | |
26 | commands = {envpython} -m check_manifest |