-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql.py
211 lines (160 loc) · 6.22 KB
/
sql.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
"""Handle SQL Strings, for generating where clauses etc
Base classes from pypika are imported exposed here
See https://github.com/kayak/pypika
"""
# from pypika import Query, Table, Schema
from arcproapi.common import columns_delim
from funclite.stringslib import get_between as _getb
def query_where_in(field_name: str, values: (tuple, str, list), datasource: str = '', override_field_delim: str = '', exclude_none: bool = False):
"""(str, iter, str) -> str
build a simple where IN ( query
Args:
field_name (str): name of column to query
values (tuple, str, list): iterable or single value to match
datasource (str):
path to datasource, passed to columns_delim to add delimited for field_name
see https://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-functions/addfielddelimiters.htm
override_field_delim (str): override the field delim
exclude_none (bool): Exclude None values from the where. The None value can cause an error to be raised when using the where for da.<Cursor>, with an error that misdirects you to think the columns are invalid.
Returns:
str: the query string
Notes:
Consider using pypika for complex queries. https://github.com/kayak/pypika
Field delims:
file gdbs & shapefiles = "
Personal gdbs = []
ArcSDE = <No delimiters>
Examples:
>>> query_where_in('ID', (123,345), 'c:/temp/my.gdb')
'"ID" IN (123, 345)'
"""
if isinstance(values, str): values = [values]
if exclude_none:
values = [v for v in values if v is not None]
def _f(v):
if isinstance(v, str):
return "'%s'" % v
return str(v)
# not currently used
def _getdelim(v):
if override_field_delim:
return '%s%s%s' % (override_field_delim, v, override_field_delim)
return columns_delim(field_name, datasource)
if isinstance(values, (int, float, str)):
values = (values,)
lst = [_f(s) for s in values]
sql = '%s IN (%s)' % (field_name, ','.join(lst))
return sql
def query_where_not_in(field_name: str, values: (tuple, str, list), datasource: str = '', override_field_delim: str = '', exclude_none: bool = False):
"""(str, iter, str) -> str
build a simple where NOT IN ( query
Args:
field_name (str): name of column to query
values (tuple, str, list): iterable or single value to match
datasource (str):
path to datasource, passed to columns_delim to add delimited for field_name
see https://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-functions/addfielddelimiters.htm
override_field_delim (str): override the field delim
exclude_none (bool): Exclude None values from the where. The None value can cause an error to be raised when using the where for da.<Cursor>, with an error that misdirects you to think the columns are invalid.
Returns:
str: the query string
Notes:
Consider using pypika for complex queries. https://github.com/kayak/pypika
Field delims:
file gdbs & shapefiles = "
Personal gdbs = []
ArcSDE = <No delimiters>
Examples:
>>> query_where_in('ID', (123,345), 'c:/temp/my.gdb')
'"ID" IN (123, 345)'
"""
if isinstance(values, str): values = [values]
if exclude_none:
values = [v for v in values if v is not None]
def _f(v):
if isinstance(v, str):
return "'%s'" % v
return str(v)
# not currently used
def _getdelim(v):
if override_field_delim:
return '%s%s%s' % (override_field_delim, v, override_field_delim)
return columns_delim(field_name, datasource)
if isinstance(values, (int, float, str)):
values = (values,)
lst = [_f(s) for s in values]
sql = '%s NOT IN (%s)' % (field_name, ','.join(lst))
return sql
def strip_where(sql):
"""(str)->str
Get everything after the where clause in a string
May fail with multiple wheres
Example:
>>> strip_where("select * from tbl where cola=1")
'cola=1'
"""
sql += '|||||||'
sql = _getb(sql, 'WHERE', '|||||||')
return sql
def query_where_and(datasource: str = '', **kwargs) -> str:
""" Generates an SQL WHERE matching the kwargs passed.
Args:
datasource (str): The datasource, can be shapefile path, or path to a database. Used to get the correct column delimiters. Uses current workspace if evaluates to False.
kwargs: The keyword arguments from which to build the ANDed where.
Returns:
str: The query
Examples:
>>> query_where_and(a=1, b='here')
'a=1 AND b="here"'
"""
sql = list()
if kwargs:
sql.append(" 1=1 " + " AND ".join("%s = '%s'" % (columns_delim(k, datasource), v)
for k, v in kwargs.items()))
sql.append(";")
return "".join(sql)
def is_not_null(fld: str) -> str:
"""
More a memory aid for the syntax for now
Args:
fld (str): field to get as is not null
Returns:
definition query compatible is not null
Examples:
>>> is_not_null('CRN')
'CRN IS NOT NULL'
"""
return '%s IS NOT NULL' % fld
def is_null(fld: str) -> str:
"""
More a memory aid for the syntax for now
Args:
fld (str): field to get as is not null
Returns:
definition query compatible is not null
Examples:
>>> is_null('CRN')
'CRN IS NULL'
"""
return '%s IS NULL' % fld
def str_starts_with(fld: str, starts_with: str) -> str:
"""
fld starts with
Args:
fld (str): field
starts_with (str): what it starts with, e.g. 'A'
Returns:
str: the query
"""
return "%s LIKE '%s%%'" % (fld, starts_with)
def str_not_start_with_digit(fld) -> str:
"""
fld not start with digit
Args:
fld (str): field
Returns:
str: the query
"""
s = "{0} NOT LIKE '0%' And {0} NOT LIKE '1%' And {0} NOT LIKE '2%' And {0} NOT LIKE '3%' And {0} NOT LIKE '4%' And {0} NOT LIKE '5%' And {0} NOT LIKE '6%' And {0} NOT LIKE '7%' And {0} NOT LIKE '8%' And {0} NOT LIKE '9%'".format(
fld)
return s