Skip to content

Commit 30c1970

Browse files
committed
adding new sqlalchemy code examples
1 parent cf81748 commit 30c1970

File tree

107 files changed

+1714
-394
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

107 files changed

+1714
-394
lines changed

content/pages/02-development-environments/19-git.markdown

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,11 @@ workflow. These resources will come in handy for specific Git subjects.
169169
the Git history, and good practices for using Git based on the
170170
knowledge of how it works internally.
171171

172+
* [Chasing a bad commit](https://vishaltelangre.com/chasing-a-bad-commit/)
173+
examines the `git bisect` command and how it can be used in either
174+
interactive mode or on its own with `git bisect run` to find the
175+
problematic code commit that needs to be fixed.
176+
172177
* [How Microsoft uses Git](https://docs.microsoft.com/en-us/azure/devops/learn/devops-at-microsoft/use-git-microsoft)
173178
gives a high-level overview of their repository structure and hosting
174179
at the extremely large scale organization.

content/pages/examples/sqlalchemy/sqlalchemy-dialects-mysql.markdown

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,3 +116,96 @@ class ModelConverter:
116116

117117
```
118118

119+
120+
## Example 2 from sqlalchemy-datatables
121+
[sqlalchemy-datatables](https://github.com/Pegase745/sqlalchemy-datatables)
122+
([PyPI package information](https://pypi.org/project/sqlalchemy-datatables/))
123+
is a helper library that makes it easier to use [SQLAlchemy](/sqlalchemy.html)
124+
with the jQuery [JavaScript](/javascript.html)
125+
[DataTables](https://datatables.net/) plugin. This library is designed to
126+
be [web framework](/web-frameworks.html) agnostic and provides code examples
127+
for both [Flask](/flask.html) and [Pyramid](/pyramid.html).
128+
129+
The project is built and maintained by
130+
[Michel Nemnom (Pegase745)](https://github.com/Pegase745) and is open
131+
sourced under the
132+
[MIT license](https://github.com/Pegase745/sqlalchemy-datatables/blob/master/LICENSE).
133+
134+
[**sqlalchemy-datatables / datatables / datatables.py**](https://github.com/Pegase745/sqlalchemy-datatables/blob/master/./datatables/datatables.py)
135+
136+
```python
137+
# datatables.py
138+
from __future__ import absolute_import
139+
140+
import math
141+
142+
from sqlalchemy import Text, func, or_
143+
~~from sqlalchemy.dialects import mysql, postgresql, sqlite
144+
145+
from datatables.clean_regex import clean_regex
146+
from datatables.search_methods import SEARCH_METHODS
147+
148+
149+
class DataTables:
150+
151+
def __init__(self, request, query, columns, allow_regex_searches=False):
152+
self.params = dict(request)
153+
if 'sEcho' in self.params:
154+
raise ValueError(
155+
'Legacy datatables not supported, upgrade to >=1.10')
156+
self.query = query
157+
self.columns = columns
158+
self.results = None
159+
self.allow_regex_searches = allow_regex_searches
160+
161+
self.cardinality_filtered = 0
162+
163+
self.cardinality = 0
164+
165+
self.yadcf_params = []
166+
self.filter_expressions = []
167+
self.error = None
168+
169+
170+
## ... source file abbreviated to get to mysql examples ...
171+
172+
173+
direction = self.params.get('order[{:d}][dir]'.format(i))
174+
sort_expr = column.sqla_expr
175+
if direction == 'asc':
176+
sort_expr = sort_expr.asc()
177+
elif direction == 'desc':
178+
sort_expr = sort_expr.desc()
179+
else:
180+
raise ValueError(
181+
'Invalid order direction: {}'.format(direction))
182+
if column.nulls_order:
183+
if column.nulls_order == 'nullsfirst':
184+
sort_expr = sort_expr.nullsfirst()
185+
elif column.nulls_order == 'nullslast':
186+
sort_expr = sort_expr.nullslast()
187+
else:
188+
raise ValueError(
189+
'Invalid order direction: {}'.format(direction))
190+
191+
sort_expressions.append(sort_expr)
192+
i += 1
193+
self.sort_expressions = sort_expressions
194+
195+
def _get_regex_operator(self):
196+
if isinstance(self.query.session.bind.dialect, postgresql.dialect):
197+
return '-'
198+
~~ elif isinstance(self.query.session.bind.dialect, mysql.dialect):
199+
return 'REGEXP'
200+
elif isinstance(self.query.session.bind.dialect, sqlite.dialect):
201+
return 'REGEXP'
202+
else:
203+
raise NotImplementedError(
204+
'Regex searches are not implemented for this dialect')
205+
206+
207+
208+
## ... source file continues with no further mysql examples...
209+
210+
```
211+

content/pages/examples/sqlalchemy/sqlalchemy-dialects-postgresql-array.markdown

Lines changed: 156 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,162 @@ meta: Python example code for the ARRAY constant from the sqlalchemy.dialects.po
1010
ARRAY is a constant within the sqlalchemy.dialects.postgresql module of the SQLAlchemy project.
1111

1212

13-
## Example 1 from sqlalchemy-utils
13+
## Example 1 from sqlacodegen
14+
[sqlacodegen](https://github.com/agronholm/sqlacodegen)
15+
([PyPI package information](https://pypi.org/project/sqlacodegen/))
16+
is a tool for
17+
reading from an existing [relational database](/databases.html) to
18+
generate code to create [SQLAlchemy](/sqlalchemy.html) models based
19+
on that database. The project is primarily written and maintained
20+
by [Alex Grönholm (agronholm)](https://github.com/agronholm) and it
21+
is open sourced under the
22+
[MIT license](https://github.com/agronholm/sqlacodegen/blob/master/LICENSE).
23+
24+
[**sqlacodegen / sqlacodegen / codegen.py**](https://github.com/agronholm/sqlacodegen/blob/master/sqlacodegen/./codegen.py)
25+
26+
```python
27+
# codegen.py
28+
from __future__ import unicode_literals, division, print_function, absolute_import
29+
30+
import inspect
31+
import re
32+
import sys
33+
from collections import defaultdict
34+
from importlib import import_module
35+
from inspect import ArgSpec
36+
from keyword import iskeyword
37+
38+
import sqlalchemy
39+
import sqlalchemy.exc
40+
from sqlalchemy import (
41+
Enum, ForeignKeyConstraint, PrimaryKeyConstraint, CheckConstraint, UniqueConstraint, Table,
42+
Column, Float)
43+
from sqlalchemy.schema import ForeignKey
44+
from sqlalchemy.sql.sqltypes import NullType
45+
from sqlalchemy.types import Boolean, String
46+
from sqlalchemy.util import OrderedDict
47+
48+
try:
49+
from sqlalchemy import ARRAY
50+
except ImportError:
51+
~~ from sqlalchemy.dialects.postgresql import ARRAY
52+
53+
try:
54+
from sqlalchemy import Computed
55+
except ImportError:
56+
Computed = None
57+
58+
try:
59+
import geoalchemy2 # noqa: F401
60+
except ImportError:
61+
pass
62+
63+
_re_boolean_check_constraint = re.compile(r"(?:(?:.*?)\.)?(.*?) IN \(0, 1\)")
64+
_re_column_name = re.compile(r'(?:(["`]?)(?:.*)\1\.)?(["`]?)(.*)\2')
65+
_re_enum_check_constraint = re.compile(r"(?:(?:.*?)\.)?(.*?) IN \((.+)\)")
66+
_re_enum_item = re.compile(r"'(.*?)(?<!\\)'")
67+
_re_invalid_identifier = re.compile(r'[^a-zA-Z0-9_]' if sys.version_info[0] < 3 else r'(?u)\W')
68+
69+
70+
class _DummyInflectEngine(object):
71+
@staticmethod
72+
def singular_noun(noun):
73+
return noun
74+
75+
76+
77+
78+
## ... source file abbreviated to get to ARRAY examples ...
79+
80+
81+
names.add(name)
82+
83+
84+
class Model(object):
85+
def __init__(self, table):
86+
super(Model, self).__init__()
87+
self.table = table
88+
self.schema = table.schema
89+
90+
for column in table.columns:
91+
if not isinstance(column.type, NullType):
92+
column.type = self._get_adapted_type(column.type, column.table.bind)
93+
94+
def _get_adapted_type(self, coltype, bind):
95+
compiled_type = coltype.compile(bind.dialect)
96+
for supercls in coltype.__class__.__mro__:
97+
if not supercls.__name__.startswith('_') and hasattr(supercls, '__visit_name__'):
98+
kw = {}
99+
if supercls is Enum:
100+
kw['name'] = coltype.name
101+
102+
new_coltype = coltype.adapt(supercls)
103+
for key, value in kw.items():
104+
setattr(new_coltype, key, value)
105+
106+
~~ if isinstance(coltype, ARRAY):
107+
new_coltype.item_type = self._get_adapted_type(new_coltype.item_type, bind)
108+
109+
try:
110+
if new_coltype.compile(bind.dialect) != compiled_type:
111+
if not isinstance(new_coltype, Float) and \
112+
not (isinstance(new_coltype, ARRAY) and
113+
isinstance(new_coltype.item_type, Float)):
114+
break
115+
except sqlalchemy.exc.CompileError:
116+
break
117+
118+
coltype = new_coltype
119+
if supercls.__name__ != supercls.__name__.upper():
120+
break
121+
122+
return coltype
123+
124+
def add_imports(self, collector):
125+
if self.table.columns:
126+
collector.add_import(Column)
127+
128+
for column in self.table.columns:
129+
collector.add_import(column.type)
130+
if column.server_default:
131+
if isinstance(column.server_default, Computed):
132+
collector.add_literal_import('sqlalchemy', 'Computed')
133+
else:
134+
collector.add_literal_import('sqlalchemy', 'text')
135+
136+
~~ if isinstance(column.type, ARRAY):
137+
collector.add_import(column.type.item_type.__class__)
138+
139+
for constraint in sorted(self.table.constraints, key=_get_constraint_sort_key):
140+
if isinstance(constraint, ForeignKeyConstraint):
141+
if len(constraint.columns) > 1:
142+
collector.add_literal_import('sqlalchemy', 'ForeignKeyConstraint')
143+
else:
144+
collector.add_literal_import('sqlalchemy', 'ForeignKey')
145+
elif isinstance(constraint, UniqueConstraint):
146+
if len(constraint.columns) > 1:
147+
collector.add_literal_import('sqlalchemy', 'UniqueConstraint')
148+
elif not isinstance(constraint, PrimaryKeyConstraint):
149+
collector.add_import(constraint)
150+
151+
for index in self.table.indexes:
152+
if len(index.columns) > 1:
153+
collector.add_import(index)
154+
155+
@staticmethod
156+
def _convert_to_valid_identifier(name):
157+
assert name, 'Identifier cannot be empty'
158+
if name[0].isdigit() or iskeyword(name):
159+
name = '_' + name
160+
elif name == 'metadata':
161+
162+
163+
## ... source file continues with no further ARRAY examples...
164+
165+
```
166+
167+
168+
## Example 2 from sqlalchemy-utils
14169
[sqlalchemy-utils](https://github.com/kvesteri/sqlalchemy-utils)
15170
([project documentation](https://sqlalchemy-utils.readthedocs.io/en/latest/)
16171
and

content/pages/examples/sqlalchemy/sqlalchemy-dialects-postgresql.markdown

Lines changed: 96 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,102 @@ class ModelConverter:
199199
```
200200

201201

202-
## Example 3 from sqlalchemy-utils
202+
## Example 3 from sqlalchemy-datatables
203+
[sqlalchemy-datatables](https://github.com/Pegase745/sqlalchemy-datatables)
204+
([PyPI package information](https://pypi.org/project/sqlalchemy-datatables/))
205+
is a helper library that makes it easier to use [SQLAlchemy](/sqlalchemy.html)
206+
with the jQuery [JavaScript](/javascript.html)
207+
[DataTables](https://datatables.net/) plugin. This library is designed to
208+
be [web framework](/web-frameworks.html) agnostic and provides code examples
209+
for both [Flask](/flask.html) and [Pyramid](/pyramid.html).
210+
211+
The project is built and maintained by
212+
[Michel Nemnom (Pegase745)](https://github.com/Pegase745) and is open
213+
sourced under the
214+
[MIT license](https://github.com/Pegase745/sqlalchemy-datatables/blob/master/LICENSE).
215+
216+
[**sqlalchemy-datatables / datatables / datatables.py**](https://github.com/Pegase745/sqlalchemy-datatables/blob/master/./datatables/datatables.py)
217+
218+
```python
219+
# datatables.py
220+
from __future__ import absolute_import
221+
222+
import math
223+
224+
from sqlalchemy import Text, func, or_
225+
~~from sqlalchemy.dialects import mysql, postgresql, sqlite
226+
227+
from datatables.clean_regex import clean_regex
228+
from datatables.search_methods import SEARCH_METHODS
229+
230+
231+
class DataTables:
232+
233+
def __init__(self, request, query, columns, allow_regex_searches=False):
234+
self.params = dict(request)
235+
if 'sEcho' in self.params:
236+
raise ValueError(
237+
'Legacy datatables not supported, upgrade to >=1.10')
238+
self.query = query
239+
self.columns = columns
240+
self.results = None
241+
self.allow_regex_searches = allow_regex_searches
242+
243+
self.cardinality_filtered = 0
244+
245+
self.cardinality = 0
246+
247+
self.yadcf_params = []
248+
self.filter_expressions = []
249+
self.error = None
250+
251+
252+
## ... source file abbreviated to get to postgresql examples ...
253+
254+
255+
column_nr = int(self.params.get('order[{:d}][column]'.format(i)))
256+
column = self.columns[column_nr]
257+
direction = self.params.get('order[{:d}][dir]'.format(i))
258+
sort_expr = column.sqla_expr
259+
if direction == 'asc':
260+
sort_expr = sort_expr.asc()
261+
elif direction == 'desc':
262+
sort_expr = sort_expr.desc()
263+
else:
264+
raise ValueError(
265+
'Invalid order direction: {}'.format(direction))
266+
if column.nulls_order:
267+
if column.nulls_order == 'nullsfirst':
268+
sort_expr = sort_expr.nullsfirst()
269+
elif column.nulls_order == 'nullslast':
270+
sort_expr = sort_expr.nullslast()
271+
else:
272+
raise ValueError(
273+
'Invalid order direction: {}'.format(direction))
274+
275+
sort_expressions.append(sort_expr)
276+
i += 1
277+
self.sort_expressions = sort_expressions
278+
279+
def _get_regex_operator(self):
280+
~~ if isinstance(self.query.session.bind.dialect, postgresql.dialect):
281+
return '-'
282+
elif isinstance(self.query.session.bind.dialect, mysql.dialect):
283+
return 'REGEXP'
284+
elif isinstance(self.query.session.bind.dialect, sqlite.dialect):
285+
return 'REGEXP'
286+
else:
287+
raise NotImplementedError(
288+
'Regex searches are not implemented for this dialect')
289+
290+
291+
292+
## ... source file continues with no further postgresql examples...
293+
294+
```
295+
296+
297+
## Example 4 from sqlalchemy-utils
203298
[sqlalchemy-utils](https://github.com/kvesteri/sqlalchemy-utils)
204299
([project documentation](https://sqlalchemy-utils.readthedocs.io/en/latest/)
205300
and

0 commit comments

Comments
 (0)