Save the object's metadata into the library database. :param fields: the fields to be stored. If not specified, all fields will be.
(self, fields: Iterable[str] | None = None)
| 588 | # Database interaction (CRUD methods). |
| 589 | |
| 590 | def store(self, fields: Iterable[str] | None = None): |
| 591 | """Save the object's metadata into the library database. |
| 592 | :param fields: the fields to be stored. If not specified, all fields |
| 593 | will be. |
| 594 | """ |
| 595 | if fields is None: |
| 596 | fields = self._fields |
| 597 | |
| 598 | # Build assignments for query. |
| 599 | assignments = [] |
| 600 | subvars: list[SQLiteType] = [] |
| 601 | for key in fields: |
| 602 | if key != "id" and key in self._dirty: |
| 603 | self._dirty.remove(key) |
| 604 | assignments.append(f"{key}=?") |
| 605 | value = self._type(key).to_sql(self[key]) |
| 606 | subvars.append(value) |
| 607 | |
| 608 | with self.db.transaction() as tx: |
| 609 | # Main table update. |
| 610 | if assignments: |
| 611 | query = f"UPDATE {self._table} SET {','.join(assignments)} WHERE id=?" |
| 612 | subvars.append(self.id) |
| 613 | tx.mutate(query, subvars) |
| 614 | |
| 615 | # Modified/added flexible attributes. |
| 616 | for key, value in self._values_flex.items(): |
| 617 | if key in self._dirty: |
| 618 | self._dirty.remove(key) |
| 619 | value = self._type(key).to_sql(value) |
| 620 | tx.mutate( |
| 621 | f"INSERT INTO {self._flex_table} " |
| 622 | "(entity_id, key, value) " |
| 623 | "VALUES (?, ?, ?);", |
| 624 | (self.id, key, value), |
| 625 | ) |
| 626 | |
| 627 | # Deleted flexible attributes. |
| 628 | for key in self._dirty: |
| 629 | tx.mutate( |
| 630 | f"DELETE FROM {self._flex_table} WHERE entity_id=? AND key=?", |
| 631 | (self.id, key), |
| 632 | ) |
| 633 | |
| 634 | self.clear_dirty() |
| 635 | |
| 636 | def load(self): |
| 637 | """Refresh the object's metadata from the library database. |