forked from metabrainz/messybrainz-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanage.py
304 lines (244 loc) · 11.9 KB
/
manage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
from messybrainz import db
from messybrainz.db.artist import truncate_recording_artist_join,\
fetch_and_store_artist_mbids_for_all_recording_mbids,\
create_artist_credit_clusters,\
truncate_artist_credit_cluster_and_redirect_tables
from messybrainz.db import release
from messybrainz.webserver import create_app
from brainzutils import musicbrainz_db
from sqlalchemy import text
import subprocess
import os
import click
import logging
import messybrainz.default_config as config
try:
import messybraiz.custom_config as config
except ImportError:
pass
from messybrainz.db.recording import create_recording_clusters,\
truncate_recording_cluster_and_recording_redirect_table
ADMIN_SQL_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'admin', 'sql')
cli = click.Group()
@cli.command()
@click.option("--host", "-h", default="0.0.0.0", show_default=True)
@click.option("--port", "-p", default=8080, show_default=True)
@click.option("--debug", "-d", is_flag=True,
help="Turns debugging mode on or off. If specified, overrides "
"'DEBUG' value in the config file.")
def runserver(host, port, debug=False):
create_app(debug=debug).run(host=host, port=port)
@cli.command()
@click.option("--force", "-f", is_flag=True, help="Drop existing database and user.")
def init_db(force):
"""Initializes database.
This process involves several steps:
1. Table structure is created.
2. Primary keys and foreign keys are created.
3. Indexes are created.
"""
db.init_db_engine(config.POSTGRES_ADMIN_URI)
if force:
exit_code = db.run_sql_script_without_transaction(os.path.join(ADMIN_SQL_DIR, 'drop_db.sql'))
if not exit_code:
raise Exception('Failed to drop existing database and user! Exit code: %i' % exit_code)
print('Creating user and a database...')
exit_code = db.run_sql_script_without_transaction(os.path.join(ADMIN_SQL_DIR, 'create_db.sql'))
if not exit_code:
raise Exception('Failed to create new database and user! Exit code: %i' % exit_code)
print('Creating database extensions...')
exit_code = db.run_sql_script_without_transaction(os.path.join(ADMIN_SQL_DIR, 'create_extensions.sql'))
app = create_app()
with app.app_context():
print('Creating tables...')
db.run_sql_script(os.path.join(ADMIN_SQL_DIR, 'create_tables.sql'))
print('Creating primary and foreign keys...')
db.run_sql_script(os.path.join(ADMIN_SQL_DIR, 'create_primary_keys.sql'))
db.run_sql_script(os.path.join(ADMIN_SQL_DIR, 'create_foreign_keys.sql'))
print('Creating indexes...')
db.run_sql_script(os.path.join(ADMIN_SQL_DIR, 'create_indexes.sql'))
print('Creating functions...')
db.run_sql_script(os.path.join(ADMIN_SQL_DIR, 'create_functions.sql'))
print("Done!")
@cli.command()
@click.option("--force", "-f", is_flag=True, help="Drop existing database and user.")
def init_test_db(force=False):
"""Same as `init_db` command, but creates a database that will be used to run tests.
`TEST_SQLALCHEMY_DATABASE_URI` variable must be defined in the config file.
"""
db.init_db_engine(config.POSTGRES_ADMIN_URI)
if force:
exit_code = db.run_sql_script_without_transaction(os.path.join(ADMIN_SQL_DIR, 'drop_test_db.sql'))
if not exit_code:
raise Exception('Failed to drop existing database and user! Exit code: %i' % exit_code)
print('Creating database and user for testing...')
exit_code = db.run_sql_script_without_transaction(os.path.join(ADMIN_SQL_DIR, 'create_test_db.sql'))
if not exit_code:
raise Exception('Failed to create new database and user! Exit code: %i' % exit_code)
exit_code = db.run_sql_script_without_transaction(os.path.join(ADMIN_SQL_DIR, 'create_extensions.sql'))
if not exit_code:
raise Exception('Failed to create database extensions! Exit code: %i' % exit_code)
db.init_db_engine(config.TEST_SQLALCHEMY_DATABASE_URI)
db.run_sql_script(os.path.join(ADMIN_SQL_DIR, 'create_tables.sql'))
db.run_sql_script(os.path.join(ADMIN_SQL_DIR, 'create_primary_keys.sql'))
db.run_sql_script(os.path.join(ADMIN_SQL_DIR, 'create_foreign_keys.sql'))
db.run_sql_script(os.path.join(ADMIN_SQL_DIR, 'create_indexes.sql'))
db.run_sql_script(os.path.join(ADMIN_SQL_DIR, 'create_functions.sql'))
print("Done!")
@cli.command()
def create_recording_clusters_for_mbids():
"""Creates clusters for recording using recording MBIDs present in
recording_json table.
"""
db.init_db_engine(config.SQLALCHEMY_DATABASE_URI)
try:
clusters_modified, clusters_add_to_redirect = create_recording_clusters()
print("Clusters modified: {0}.".format(clusters_modified))
print("Clusters add to redirect table: {0}.".format(clusters_add_to_redirect))
print ("Done!")
except Exception as error:
print("While creating recording clusters. An error occured: {0}".format(error))
raise
@cli.command()
def truncate_recording_cluster_and_redirect():
"""Truncate recording_cluster and recording_redirect tables."""
db.init_db_engine(config.SQLALCHEMY_DATABASE_URI)
try:
truncate_recording_cluster_and_recording_redirect_table()
print("recording_cluster and recording_redirect table truncated.")
except Exception as error:
print("An error occured while truncating recording_cluster and recording_redirect: {0}".format(error))
raise
@cli.command()
def fetch_and_store_artist_mbids():
""" Fetches artist MBIDs from the musicbrainz database for the recording MBIDs
in the recording_json table submitted while submitting a listen. It fetches
only the artist MBIDs for the recordings MBIDs which are not in recording_artist_join
table. In the end it prints to the console the total recording MBIDs it processed
and the total recording MBIDs it added to the recording_artist_join table.
"""
# Init databases
db.init_db_engine(config.SQLALCHEMY_DATABASE_URI)
musicbrainz_db.init_db_engine(config.MB_DATABASE_URI)
try:
num_recording_mbids_processed, num_recording_mbids_added = fetch_and_store_artist_mbids_for_all_recording_mbids()
print("Total recording MBIDs processed: {0}.".format(num_recording_mbids_processed))
print("Total recording MBIDs added to table: {0}.".format(num_recording_mbids_added))
print("Done!")
except Exception as error:
print("Unable to fetch artist MBIDs. An error occured: {0}".format(error))
raise
@cli.command()
def truncate_recording_artist_join_table():
"""Truncate table recording_artist_join."""
db.init_db_engine(config.SQLALCHEMY_DATABASE_URI)
try:
truncate_recording_artist_join()
print("Table recording_artist_join truncated.")
except Exception as error:
print("An error occured while truncating tables: {0}".format(error))
raise
@cli.command()
@click.option("--verbose", "-v", default=0, help="Print debug information for given verbose level(0,1,2).")
def create_artist_credit_clusters_for_mbids(verbose=0):
"""Creates clusters for artist_credits using artist MBIDs present in
recording_json table.
"""
if verbose == 1:
logging.basicConfig(format='%(message)s', level=logging.INFO)
elif verbose == 2:
logging.basicConfig(format='%(message)s', level=logging.DEBUG)
print("Creating artist_credit clusters...")
db.init_db_engine(config.SQLALCHEMY_DATABASE_URI)
try:
logging.debug("=" * 80)
clusters_modified, clusters_add_to_redirect = create_artist_credit_clusters()
logging.debug("=" * 80)
print("Clusters modified: {0}.".format(clusters_modified))
print("Clusters add to redirect table: {0}.".format(clusters_add_to_redirect))
print("Done!")
except Exception as error:
print("While creating artist_credit clusters. An error occured: {0}".format(error))
raise
@cli.command()
@click.option("--verbose", "-v", default=0, help="Print debug information for given verbose level(0,1,2).")
def create_release_clusters_for_mbids(verbose=0):
"""Creates clusters for release using release MBIDs present in
recording_json table.
"""
if verbose == 1:
logging.basicConfig(format='%(message)s', level=logging.INFO)
elif verbose == 2:
logging.basicConfig(format='%(message)s', level=logging.DEBUG)
print("Creating release clusters...")
db.init_db_engine(config.SQLALCHEMY_DATABASE_URI)
try:
logging.info("=" * 80)
clusters_modified, clusters_add_to_redirect = release.create_release_clusters()
logging.info("=" * 80)
print("Clusters modified: {0}.".format(clusters_modified))
print("Clusters add to redirect table: {0}.".format(clusters_add_to_redirect))
print ("Done!")
except Exception as error:
print("While creating release clusters. An error occured: {0}".format(error))
raise
@cli.command()
def truncate_artist_credit_cluster_and_redirect():
"""Truncate artist_credit_cluster and artist_credit_redirect table."""
logging.basicConfig(format='%(message)s', level=logging.INFO)
db.init_db_engine(config.SQLALCHEMY_DATABASE_URI)
try:
truncate_artist_credit_cluster_and_redirect_tables()
logging.info("artist_credit_cluster and artist_credit_redirect table truncated.")
except Exception as error:
logging.error("An error occured while truncating artist_credit_cluster"
"and artist_credit_redirect table: {0}".format(error)
)
raise
@cli.command()
def truncate_release_cluster_and_redirect():
"""Truncate release_cluster and release_redirect tables."""
db.init_db_engine(config.SQLALCHEMY_DATABASE_URI)
try:
release.truncate_release_cluster_and_release_redirect_table()
print("release_cluster and release_redirect table truncated.")
except Exception as error:
print("An error occured while truncating release_cluster and release_redirect: {0}".format(error))
raise
@cli.command()
@click.option("--verbose", "-v", is_flag=True, help="Print debug information.")
def fetch_and_store_releases(verbose=False):
""" Fetches releases from the musicbrainz database for the recording MBIDs
in the recording_json table submitted while submitting a listen. It fetches
only the releases for the recordings MBIDs which are not in recording_release_join
table. In the end it prints to the console the total recording MBIDs it processed
and the total recording MBIDs it added to the recording_release_join table.
"""
print("Fetching release for recording MBIDs...")
if verbose:
logging.basicConfig(format='%(message)s', level=logging.DEBUG)
# Init databases
db.init_db_engine(config.SQLALCHEMY_DATABASE_URI)
musicbrainz_db.init_db_engine(config.MB_DATABASE_URI)
try:
logging.debug("=" * 80)
num_recording_mbids_processed, num_recording_mbids_added = release.fetch_and_store_releases_for_all_recording_mbids()
logging.debug("=" * 80)
print("Total recording MBIDs processed: {0}.".format(num_recording_mbids_processed))
print("Total recording MBIDs added to table: {0}.".format(num_recording_mbids_added))
print("Done!")
except Exception as error:
print("Unable to fetch releases. An error occured: {0}".format(error))
raise
@cli.command()
def truncate_recording_release_join_table():
"""Truncate table recording_release_join."""
db.init_db_engine(config.SQLALCHEMY_DATABASE_URI)
try:
release.truncate_recording_release_join()
print("Table recording_release_join truncated.")
except Exception as error:
print("An error occured while truncating recording_release_join table: {0}".format(error))
raise
if __name__ == '__main__':
cli()