-
Notifications
You must be signed in to change notification settings - Fork 2k
/
plugin.py
287 lines (236 loc) · 10.1 KB
/
plugin.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# encoding: utf-8
import logging
import ckan.plugins as p
import ckan.logic as logic
import ckan.model as model
from ckan.model.core import State
import ckanext.datastore.helpers as datastore_helpers
import ckanext.datastore.logic.action as action
import ckanext.datastore.logic.auth as auth
import ckanext.datastore.interfaces as interfaces
from ckanext.datastore.backend import (
DatastoreException,
_parse_sort_clause,
DatastoreBackend
)
from ckanext.datastore.backend.postgres import DatastorePostgresqlBackend
log = logging.getLogger(__name__)
_get_or_bust = logic.get_or_bust
DEFAULT_FORMATS = []
ValidationError = p.toolkit.ValidationError
class DatastorePlugin(p.SingletonPlugin):
p.implements(p.IConfigurable, inherit=True)
p.implements(p.IConfigurer)
p.implements(p.IActions)
p.implements(p.IAuthFunctions)
p.implements(p.IResourceUrlChange)
p.implements(p.IDomainObjectModification, inherit=True)
p.implements(p.IRoutes, inherit=True)
p.implements(p.IResourceController, inherit=True)
p.implements(p.ITemplateHelpers)
p.implements(p.IForkObserver, inherit=True)
p.implements(interfaces.IDatastore, inherit=True)
p.implements(interfaces.IDatastoreBackend, inherit=True)
legacy_mode = False
resource_show_action = None
def __new__(cls, *args, **kwargs):
idatastore_extensions = p.PluginImplementations(interfaces.IDatastore)
idatastore_extensions = idatastore_extensions.extensions()
if idatastore_extensions and idatastore_extensions[0].__class__ != cls:
msg = ('The "datastore" plugin must be the first IDatastore '
'plugin loaded. Change the order it is loaded in '
'"ckan.plugins" in your CKAN .ini file and try again.')
raise DatastoreException(msg)
return super(cls, cls).__new__(cls, *args, **kwargs)
# IDatastoreBackend
def register_backends(self):
return {
'postgresql': DatastorePostgresqlBackend,
'postgres': DatastorePostgresqlBackend,
}
# IConfigurer
def update_config(self, config):
DatastoreBackend.register_backends()
DatastoreBackend.set_active_backend(config)
p.toolkit.add_template_directory(config, 'templates')
self.backend = DatastoreBackend.get_active_backend()
# IConfigurable
def configure(self, config):
self.config = config
self.backend.configure(config)
# Legacy mode means that we have no read url. Consequently sql search
# is not available and permissions do not have to be changed. In
# legacy mode, the datastore runs on PG prior to 9.0 (for
# example 8.4).
if hasattr(self.backend, 'is_legacy_mode'):
self.legacy_mode = self.backend.is_legacy_mode(self.config)
# IDomainObjectModification
# IResourceUrlChange
def notify(self, entity, operation=None):
if not isinstance(entity, model.Package) or self.legacy_mode:
return
# if a resource is new, it cannot have a datastore resource, yet
if operation == model.domain_object.DomainObjectOperation.changed:
context = {'model': model, 'ignore_auth': True}
if entity.private:
func = p.toolkit.get_action('datastore_make_private')
else:
func = p.toolkit.get_action('datastore_make_public')
for resource in entity.resources:
try:
func(context, {
'connection_url': self.backend.write_url,
'resource_id': resource.id})
except p.toolkit.ObjectNotFound:
pass
# IActions
def get_actions(self):
actions = {
'datastore_create': action.datastore_create,
'datastore_upsert': action.datastore_upsert,
'datastore_delete': action.datastore_delete,
'datastore_search': action.datastore_search,
'datastore_info': action.datastore_info,
'datastore_function_create': action.datastore_function_create,
'datastore_function_delete': action.datastore_function_delete,
'datastore_run_triggers': action.datastore_run_triggers,
}
if not self.legacy_mode:
if getattr(self.backend, 'enable_sql_search', False):
# Only enable search_sql if the config does not disable it
actions.update({
'datastore_search_sql': action.datastore_search_sql,
})
actions.update({
'datastore_make_private': action.datastore_make_private,
'datastore_make_public': action.datastore_make_public})
return actions
# IAuthFunctions
def get_auth_functions(self):
return {
'datastore_create': auth.datastore_create,
'datastore_upsert': auth.datastore_upsert,
'datastore_delete': auth.datastore_delete,
'datastore_info': auth.datastore_info,
'datastore_search': auth.datastore_search,
'datastore_search_sql': auth.datastore_search_sql,
'datastore_change_permissions': auth.datastore_change_permissions,
'datastore_function_create': auth.datastore_function_create,
'datastore_function_delete': auth.datastore_function_delete,
'datastore_run_triggers': auth.datastore_run_triggers,
}
# IRoutes
def before_map(self, m):
m.connect(
'/datastore/dump/{resource_id}',
controller='ckanext.datastore.controller:DatastoreController',
action='dump')
m.connect(
'resource_dictionary', '/dataset/{id}/dictionary/{resource_id}',
controller='ckanext.datastore.controller:DatastoreController',
action='dictionary', ckan_icon='book')
return m
# IResourceController
def before_show(self, resource_dict):
# Modify the resource url of datastore resources so that
# they link to the datastore dumps.
if resource_dict.get('url_type') == 'datastore':
resource_dict['url'] = p.toolkit.url_for(
controller='ckanext.datastore.controller:DatastoreController',
action='dump', resource_id=resource_dict['id'],
qualified=True)
if 'datastore_active' not in resource_dict:
resource_dict[u'datastore_active'] = False
return resource_dict
def after_delete(self, context, resources):
model = context['model']
pkg = context['package']
res_query = model.Session.query(model.Resource)
query = res_query.filter(
model.Resource.package_id == pkg.id,
model.Resource.state == State.DELETED
)
deleted = [
res for res in query.all()
if res.extras.get('datastore_active') is True]
for res in deleted:
self.backend.delete(context, {
'resource_id': res.id,
})
res.extras['datastore_active'] = False
res_query.filter_by(id=res.id).update(
{'extras': res.extras}, synchronize_session=False)
# IDatastore
def datastore_validate(self, context, data_dict, fields_types):
column_names = fields_types.keys()
fields = data_dict.get('fields')
if fields:
data_dict['fields'] = list(set(fields) - set(column_names))
filters = data_dict.get('filters', {})
for key in filters.keys():
if key in fields_types:
del filters[key]
q = data_dict.get('q')
if q:
if isinstance(q, basestring):
del data_dict['q']
elif isinstance(q, dict):
for key in q.keys():
if key in fields_types and isinstance(q[key], basestring):
del q[key]
language = data_dict.get('language')
if language:
if isinstance(language, basestring):
del data_dict['language']
plain = data_dict.get('plain')
if plain:
if isinstance(plain, bool):
del data_dict['plain']
distinct = data_dict.get('distinct')
if distinct:
if isinstance(distinct, bool):
del data_dict['distinct']
sort_clauses = data_dict.get('sort')
if sort_clauses:
invalid_clauses = [
c for c in sort_clauses
if not _parse_sort_clause(
c, fields_types
)
]
data_dict['sort'] = invalid_clauses
limit = data_dict.get('limit')
if limit:
is_positive_int = datastore_helpers.validate_int(limit,
non_negative=True)
is_all = isinstance(limit, basestring) and limit.lower() == 'all'
if is_positive_int or is_all:
del data_dict['limit']
offset = data_dict.get('offset')
if offset:
is_positive_int = datastore_helpers.validate_int(offset,
non_negative=True)
if is_positive_int:
del data_dict['offset']
return data_dict
def datastore_delete(self, context, data_dict, fields_types, query_dict):
hook = getattr(self.backend, 'datastore_delete', None)
if hook:
query_dict = hook(context, data_dict, fields_types, query_dict)
return query_dict
def datastore_search(self, context, data_dict, fields_types, query_dict):
hook = getattr(self.backend, 'datastore_search', None)
if hook:
query_dict = hook(context, data_dict, fields_types, query_dict)
return query_dict
def get_helpers(self):
return {
'datastore_dictionary': datastore_helpers.datastore_dictionary}
# IForkObserver
def before_fork(self):
try:
before_fork = self.backend.before_fork
except AttributeError:
pass
else:
before_fork()