Rename a few files and minor cleanup
[mediagoblin.git] / mediagoblin / db / util.py
CommitLineData
1815f5ce 1# GNU MediaGoblin -- federated, autonomous media hosting
cf29e8a8 2# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
1815f5ce
CAW
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU Affero General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU Affero General Public License for more details.
13#
14# You should have received a copy of the GNU Affero General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
a050e776 16
39dc3bf8 17from mediagoblin.db.base import Session
a523ffce 18from mediagoblin.db.models import MediaEntry, Tag, MediaTag, Collection
1815f5ce 19
1e46dc25
SS
20
21##########################
22# Random utility functions
23##########################
24
25
26def atomic_update(table, query_dict, update_values):
44082b12 27 table.query.filter_by(**query_dict).update(update_values,
1e46dc25
SS
28 synchronize_session=False)
29 Session.commit()
30
31
65969d3f
SS
32def check_media_slug_used(uploader_id, slug, ignore_m_id):
33 query = MediaEntry.query.filter_by(uploader=uploader_id, slug=slug)
1e46dc25 34 if ignore_m_id is not None:
65969d3f
SS
35 query = query.filter(MediaEntry.id != ignore_m_id)
36 does_exist = query.first() is not None
1e46dc25
SS
37 return does_exist
38
39
40def media_entries_for_tag_slug(dummy_db, tag_slug):
41 return MediaEntry.query \
42 .join(MediaEntry.tags_helper) \
43 .join(MediaTag.tag_helper) \
44 .filter(
45 (MediaEntry.state == u'processed')
46 & (Tag.slug == tag_slug))
47
48
49def clean_orphan_tags(commit=True):
50 """Search for unused MediaTags and delete them"""
51 q1 = Session.query(Tag).outerjoin(MediaTag).filter(MediaTag.id==None)
52 for t in q1:
53 Session.delete(t)
54 # The "let the db do all the work" version:
55 # q1 = Session.query(Tag.id).outerjoin(MediaTag).filter(MediaTag.id==None)
56 # q2 = Session.query(Tag).filter(Tag.id.in_(q1))
57 # q2.delete(synchronize_session = False)
58 if commit:
59 Session.commit()
60
61
455fd36f 62def check_collection_slug_used(creator_id, slug, ignore_c_id):
1e46dc25
SS
63 filt = (Collection.creator == creator_id) \
64 & (Collection.slug == slug)
65 if ignore_c_id is not None:
66 filt = filt & (Collection.id != ignore_c_id)
67 does_exist = Session.query(Collection.id).filter(filt).first() is not None
68 return does_exist
69
1e46dc25
SS
70if __name__ == '__main__':
71 from mediagoblin.db.open import setup_connection_and_db_from_config
72
73 db = setup_connection_and_db_from_config({'sql_engine':'sqlite:///mediagoblin.db'})
74
75 clean_orphan_tags()