Skip to content

Commit 8e36e91

Browse files
authored
Merge pull request #369 from wackazong/python-transform
Transform algorithm in python 3
2 parents 74045be + f76a710 commit 8e36e91

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

lib/php_crud_api_transform.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
def php_crud_api_transform(tables):
2+
3+
def get_objects(tables, table_name, where_index=None, match_value=None):
4+
objects = []
5+
for record in tables[table_name]['records']:
6+
if where_index == None or (record[where_index] == match_value):
7+
object = {}
8+
columns = tables[table_name]['columns']
9+
for column in columns:
10+
index = columns.index(column)
11+
object[column] = record[index]
12+
for relation, reltable in tables.items():
13+
for key, target in reltable.get('relations', {}).items():
14+
if target == table_name + '.' + column:
15+
relcols = reltable['columns']
16+
column_indices = {value: relcols.index(value) for value in relcols}
17+
object[relation] = get_objects(
18+
tables, relation, column_indices[key], record[index])
19+
objects.append(object)
20+
return objects
21+
22+
tree = {}
23+
for name, table in tables.items():
24+
if not 'relations' in table:
25+
tree[name] = get_objects(tables, name)
26+
if 'results' in table:
27+
tree['_results'] = table['results']
28+
return tree
29+
30+
31+
if __name__ == "__main__":
32+
input = {"posts": {"columns": ["id","user_id","category_id","content"],"records": [[1,1,1,"blogstarted"]]},"post_tags": {"relations": {"post_id": "posts.id"},"columns": ["id","post_id","tag_id"],"records": [[1,1,1],[2,1,2]]},"categories": {"relations": {"id": "posts.category_id"},"columns": ["id","name"],"records": [[1,"anouncement"]]},"tags": {"relations": {"id": "post_tags.tag_id"},"columns": ["id","name"],"records": [[1,"funny"],[2,"important"]]},"comments": {"relations": {"post_id": "posts.id"},"columns": ["id","post_id","message"],"records": [[1,1,"great"],[2,1,"fantastic"]]}}
33+
output = {"posts": [{"id": 1,"post_tags": [{"id": 1,"post_id": 1,"tag_id": 1,"tags": [{"id": 1,"name": "funny"}]},{"id": 2,"post_id": 1,"tag_id": 2,"tags": [{"id": 2,"name": "important"}]}],"comments": [{"id": 1,"post_id": 1,"message": "great"},{"id": 2,"post_id": 1,"message": "fantastic"}],"user_id": 1,"category_id": 1,"categories": [{"id": 1,"name": "anouncement"}],"content": "blogstarted"}]}
34+
35+
print(php_crud_api_transform(input) == output)

0 commit comments

Comments
 (0)