Skip to content

Instantly share code, notes, and snippets.

@dpmittal
Last active March 26, 2018 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpmittal/47297f385c5c5d65d93c13bf8ae6cbdf to your computer and use it in GitHub Desktop.
Save dpmittal/47297f385c5c5d65d93c13bf8ae6cbdf to your computer and use it in GitHub Desktop.
recording.py
from collections import defaultdict
from mbdata import models
from sqlalchemy.orm import joinedload
from brainzutils import cache
from critiquebrainz.frontend.external.musicbrainz_db import mb_session, DEFAULT_CACHE_EXPIRATION
"""Example Function to get information related to recording"""
def get_recording_by_id(id, relations=None):
if relations is None:
relations = []
key = cache.gen_key(id)
recording = cache.get(key)
if not recording:
with mb_db.mb_engine.connect() as connection:
result = connection.execute(sqlalchemy.text("""
SELECT rec.id,
rec.name,
rec.artist_credit,
artist_credit.artist_count,
artist_credit.name,
array_agg(acn.name) as artist_credit_names,
array_agg(artist.gid) as artist_credit_gids,
isrc.isrc
FROM recording AS rec
INNER JOIN artist_credit
ON rec.artist_credit = artist_credit.id
INNER JOIN artist_credit_name acn
ON acn.artist_credit = artist_credit.id
INNER JOIN artist
ON artist.id = acn.artist
INNER JOIN isrc
ON rec.id = isrc.recording
WHERE rec.gid = :recording_id
GROUP BY rec.id, artist_credit.id, isrc.recording
"""),{
"recording_id" = id
})
row = result.fetchone()
recording = dict(row)
# The data fetched needs to be properly arranged
# in dictionaries.
if not rows:
raise NoDataFoundError("No data Found")
if "url-rels" in relations:
with mb_db.db_engine.connect() as connection:
result = connection.execute(sqlalchemy.text("""
SELECT url.id,
url.gid,
url.url,
link_type.name,
recording.gid,
recording.name
FROM l_recording_url
INNER JOIN url
ON url.id = l_recording_url.entity1
INNER JOIN release_group
ON l_recording_url.entity1 = recording.id
INNER JOIN link
ON l_recording_url.link = link.id
INNER JOIN link_type
ON link.link_type=link_type.id
WHERE recording.gid = :id
"""), {
"id": id,
})
url_relations = result.fetchall()
# Urls can be arranged then in a dictionary as it si being presently done for other entities
if url_relations:
recording["url-relations"] = url_relations
if "tags" in relations:
## We can use helpers for things common between entities.
## This is similar to what Search Server actually does.
tags = db_helpers.get_tags(id, 'recording', 'recording_tag', 'recording')
if tags:
recording["tags"] = tags
## Cache results as it is done presently
cache.set(key=key, val=recording, time=DEFAULT_CACHE_EXPIRATION)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment