|
0
|
1 |
""" |
|
|
2 |
A collection of utility routines and classes used by the spatial |
|
|
3 |
backends. |
|
|
4 |
""" |
|
|
5 |
|
|
|
6 |
def getstatusoutput(cmd): |
|
|
7 |
""" |
|
|
8 |
Executes a shell command on the platform using subprocess.Popen and |
|
|
9 |
return a tuple of the status and stdout output. |
|
|
10 |
""" |
|
|
11 |
from subprocess import Popen, PIPE |
|
|
12 |
# Set stdout and stderr to PIPE because we want to capture stdout and |
|
|
13 |
# prevent stderr from displaying. |
|
|
14 |
p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) |
|
|
15 |
# We use p.communicate() instead of p.wait() to avoid deadlocks if the |
|
|
16 |
# output buffers exceed POSIX buffer size. |
|
|
17 |
stdout, stderr = p.communicate() |
|
|
18 |
return p.returncode, stdout.strip() |
|
|
19 |
|
|
|
20 |
def gqn(val): |
|
|
21 |
""" |
|
|
22 |
The geographic quote name function; used for quoting tables and |
|
|
23 |
geometries (they use single rather than the double quotes of the |
|
|
24 |
backend quotename function). |
|
|
25 |
""" |
|
|
26 |
if isinstance(val, basestring): |
|
|
27 |
if isinstance(val, unicode): val = val.encode('ascii') |
|
|
28 |
return "'%s'" % val |
|
|
29 |
else: |
|
|
30 |
return str(val) |
|
|
31 |
|
|
|
32 |
class SpatialOperation(object): |
|
|
33 |
""" |
|
|
34 |
Base class for generating spatial SQL. |
|
|
35 |
""" |
|
|
36 |
def __init__(self, function='', operator='', result='', beg_subst='', end_subst=''): |
|
|
37 |
self.function = function |
|
|
38 |
self.operator = operator |
|
|
39 |
self.result = result |
|
|
40 |
self.beg_subst = beg_subst |
|
|
41 |
try: |
|
|
42 |
# Try and put the operator and result into to the |
|
|
43 |
# end substitution. |
|
|
44 |
self.end_subst = end_subst % (operator, result) |
|
|
45 |
except TypeError: |
|
|
46 |
self.end_subst = end_subst |
|
|
47 |
|
|
|
48 |
@property |
|
|
49 |
def sql_subst(self): |
|
|
50 |
return ''.join([self.beg_subst, self.end_subst]) |
|
|
51 |
|
|
|
52 |
def as_sql(self, geo_col): |
|
|
53 |
return self.sql_subst % self.params(geo_col) |
|
|
54 |
|
|
|
55 |
def params(self, geo_col): |
|
|
56 |
return (geo_col, self.operator) |
|
|
57 |
|
|
|
58 |
class SpatialFunction(SpatialOperation): |
|
|
59 |
""" |
|
|
60 |
Base class for generating spatial SQL related to a function. |
|
|
61 |
""" |
|
|
62 |
def __init__(self, func, beg_subst='%s(%s, %%s', end_subst=')', result='', operator=''): |
|
|
63 |
# Getting the function prefix. |
|
|
64 |
kwargs = {'function' : func, 'operator' : operator, 'result' : result, |
|
|
65 |
'beg_subst' : beg_subst, 'end_subst' : end_subst,} |
|
|
66 |
super(SpatialFunction, self).__init__(**kwargs) |
|
|
67 |
|
|
|
68 |
def params(self, geo_col): |
|
|
69 |
return (self.function, geo_col) |