-
Notifications
You must be signed in to change notification settings - Fork 44
/
pushpull.py
237 lines (188 loc) · 6.23 KB
/
pushpull.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
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import io
import os
import re
import six
import json
import unicodecsv as csv
from copy import deepcopy
from importlib import import_module
from tableschema import Schema
from .package import Package
from . import helpers
# Module API
def push_datapackage(descriptor, backend, **backend_options):
"""Push Data Package to storage.
All parameters should be used as keyword arguments.
Args:
descriptor (str): path to descriptor
backend (str): backend name like `sql` or `bigquery`
backend_options (dict): backend options mentioned in backend docs
"""
# Init maps
tables = []
schemas = []
datamap = {}
mapping = {}
# Init model
model = Package(descriptor)
# Get storage
plugin = import_module('jsontableschema.plugins.%s' % backend)
storage = plugin.Storage(**backend_options)
# Collect tables/schemas/data
for resource in model.resources:
if not resource.tabular:
continue
name = resource.descriptor.get('name', None)
table = _convert_path(resource.descriptor['path'], name)
schema = resource.descriptor['schema']
data = resource.table.iter(keyed=True)
# TODO: review
def values(schema, data):
for item in data:
row = []
for field in schema['fields']:
row.append(item.get(field['name'], None))
yield tuple(row)
tables.append(table)
schemas.append(schema)
datamap[table] = values(schema, data)
if name is not None:
mapping[name] = table
schemas = _convert_schemas(mapping, schemas)
# Create tables
for table in tables:
if table in storage.buckets:
storage.delete(table)
storage.create(tables, schemas)
# Write data to tables
for table in storage.buckets:
if table in datamap:
storage.write(table, datamap[table])
return storage
def pull_datapackage(descriptor, name, backend, **backend_options):
"""Pull Data Package from storage.
All parameters should be used as keyword arguments.
Args:
descriptor (str): path where to store descriptor
name (str): name of the pulled datapackage
backend (str): backend name like `sql` or `bigquery`
backend_options (dict): backend options mentioned in backend docs
"""
# Save datapackage name
datapackage_name = name
# Get storage
plugin = import_module('jsontableschema.plugins.%s' % backend)
storage = plugin.Storage(**backend_options)
# Iterate over tables
resources = []
for table in storage.buckets:
# Prepare
schema = storage.describe(table)
base = os.path.dirname(descriptor)
path, name = _restore_path(table)
fullpath = os.path.join(base, path)
# Write data
helpers.ensure_dir(fullpath)
with io.open(fullpath, 'wb') as file:
model = Schema(deepcopy(schema))
data = storage.iter(table)
writer = csv.writer(file, encoding='utf-8')
writer.writerow(model.headers)
for row in data:
writer.writerow(row)
# Add resource
resource = {'schema': schema, 'path': path}
if name is not None:
resource['name'] = name
resources.append(resource)
# Write descriptor
mode = 'w'
encoding = 'utf-8'
if six.PY2:
mode = 'wb'
encoding = None
resources = _restore_resources(resources)
helpers.ensure_dir(descriptor)
with io.open(descriptor,
mode=mode,
encoding=encoding) as file:
descriptor = {
'name': datapackage_name,
'resources': resources,
}
json.dump(descriptor, file, indent=4)
return storage
# Internal
def _convert_path(path, name):
"""Convert resource's path and name to storage's table name.
Args:
path (str): resource path
name (str): resource name
Returns:
str: table name
"""
table = os.path.splitext(path)[0]
table = table.replace(os.path.sep, '__')
if name is not None:
table = '___'.join([table, name])
table = re.sub('[^0-9a-zA-Z_]+', '_', table)
table = table.lower()
return table
def _restore_path(table):
"""Restore resource's path and name from storage's table.
Args:
table (str): table name
Returns:
(str, str): resource path and name
"""
name = None
splited = table.split('___')
path = splited[0]
if len(splited) == 2:
name = splited[1]
path = path.replace('__', os.path.sep)
path += '.csv'
return path, name
def _convert_schemas(mapping, schemas):
"""Convert schemas to be compatible with storage schemas.
Foreign keys related operations.
Args:
mapping (dict): mapping between resource name and table name
schemas (list): schemas
Raises:
ValueError: if there is no resource
for some foreign key in given mapping
Returns:
list: converted schemas
"""
schemas = deepcopy(schemas)
for schema in schemas:
for fk in schema.get('foreignKeys', []):
resource = fk['reference']['resource']
if resource != 'self':
if resource not in mapping:
message = 'Not resource "%s" for foreign key "%s"'
message = message % (resource, fk)
raise ValueError(message)
fk['reference']['resource'] = mapping[resource]
return schemas
def _restore_resources(resources):
"""Restore schemas from being compatible with storage schemas.
Foreign keys related operations.
Args:
list: resources from storage
Returns:
list: restored resources
"""
resources = deepcopy(resources)
for resource in resources:
schema = resource['schema']
for fk in schema.get('foreignKeys', []):
_, name = _restore_path(fk['reference']['resource'])
fk['reference']['resource'] = name
return resources