Skip to content

Commit a474f71

Browse files
committed
Add adding list traits
1 parent e3538f7 commit a474f71

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

pathtraits/db.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -130,13 +130,14 @@ def sql_type(value_type):
130130
sql_type = sqlite_types.get(value_type, "TEXT")
131131
return sql_type
132132

133-
def put(self, table, condition=None, **kwargs):
133+
def put(self, table, condition=None, update=True, **kwargs):
134134
"""
135135
Puts a row into a table. Creates a row if not present, updates otherwise.
136+
:param update; overwrite existing data
136137
"""
137138
escaped_kwargs = {k: TraitsDB.escape(v) for (k, v) in kwargs.items()}
138139

139-
if self.get(table, condition=condition, **kwargs):
140+
if update and self.get(table, condition=condition, **kwargs):
140141
# update
141142
values = " , ".join([f"{k}={v}" for (k, v) in escaped_kwargs.items()])
142143
if condition:
@@ -223,7 +224,7 @@ def create_trait_table(self, trait_name, value_type):
223224
self.execute(add_table_query)
224225
self.update_traits()
225226

226-
def put_trait(self, path_id, trait_name, value):
227+
def put_trait(self, path_id, trait_name, value, update=True):
227228
"""
228229
Put a trait to the database
229230
@@ -233,7 +234,7 @@ def put_trait(self, path_id, trait_name, value):
233234
:param value: trait value
234235
"""
235236
kwargs = {"path": path_id, trait_name: value}
236-
self.put(trait_name, condition=f"path = {path_id}", **kwargs)
237+
self.put(trait_name, condition=f"path = {path_id}", update=update, **kwargs)
237238

238239
def add_pathpair(self, pair: PathPair):
239240
"""
@@ -259,8 +260,17 @@ def add_pathpair(self, pair: PathPair):
259260
for k, v in traits.items():
260261
# same YAML key might have different value types
261262
# Therefore, add type to key
262-
k = f"{k}_{TraitsDB.sql_type(type(v))}"
263+
264+
# get element type for list
265+
# add: handle lists with mixed element type
266+
t = type(v[0]) if isinstance(v, list) else type(v)
267+
k = f"{k}_{TraitsDB.sql_type(t)}"
263268
if k not in self.traits:
264-
self.create_trait_table(k, type(v))
269+
t = type(v[0]) if isinstance(v, list) else type(v)
270+
self.create_trait_table(k, t)
265271
if k in self.traits:
266-
self.put_trait(path_id, k, v)
272+
if isinstance(v, list):
273+
for vv in v:
274+
self.put_trait(path_id, k, vv, update=False)
275+
else:
276+
self.put_trait(path_id, k, v)

0 commit comments

Comments
 (0)