Merge ~ack/maas:1908552-3.0 into maas:3.0

Proposed by Alberto Donato
Status: Merged
Approved by: Alberto Donato
Approved revision: b7c3a8e67a0b0ea59f27ecdadaf0be9443c86ba3
Merge reported by: MAAS Lander
Merged at revision: not available
Proposed branch: ~ack/maas:1908552-3.0
Merge into: maas:3.0
Diff against target: 65 lines (+38/-1)
2 files modified
src/maascli/snap.py (+16/-1)
src/maascli/tests/test_snap.py (+22/-0)
Reviewer Review Type Date Requested Status
Alberto Donato (community) Approve
Review via email: mp+403338@code.launchpad.net

Commit message

LP: #1908552 - only run DB migrations on init if DB is empty

To post a comment you must log in.
Revision history for this message
Alberto Donato (ack) :
review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1diff --git a/src/maascli/snap.py b/src/maascli/snap.py
2index bef3af1..5a16465 100644
3--- a/src/maascli/snap.py
4+++ b/src/maascli/snap.py
5@@ -315,6 +315,21 @@ def change_user(username, effective=False):
6 os.setuid(running_uid)
7
8
9+def db_need_init(connection=None) -> bool:
10+ """Whether the database needs initializing.
11+
12+ It assumes the database is set up if there's any table in it.
13+ """
14+ if connection is None:
15+ # local import since the CLI shouldn't unconditionally depend on Django
16+ from django.db import connection
17+
18+ try:
19+ return not connection.introspection.table_names()
20+ except Exception:
21+ return True
22+
23+
24 def migrate_db(capture=False):
25 """Migrate the database."""
26 if capture:
27@@ -645,7 +660,7 @@ class cmd_init(SnapCommand):
28 start_services,
29 )
30
31- if mode in ("region", "region+rack"):
32+ if mode in ("region", "region+rack") and db_need_init():
33 # When in 'region' or 'region+rack' the migrations for the database
34 # must be at the same level as this controller.
35 perform_work(
36diff --git a/src/maascli/tests/test_snap.py b/src/maascli/tests/test_snap.py
37index a0cf740..aee41db 100644
38--- a/src/maascli/tests/test_snap.py
39+++ b/src/maascli/tests/test_snap.py
40@@ -598,3 +598,25 @@ class TestCmdConfig(MAASTestCase):
41 config_manager.update.assert_not_called()
42 self.assertEqual(stdout.getvalue(), "")
43 mock_sighup_supervisord.assert_not_called()
44+
45+
46+class TestDBNeedInit(MAASTestCase):
47+ def test_has_tables(self):
48+ connection = MagicMock()
49+ connection.introspection.table_names.return_value = [
50+ "table1",
51+ "table2",
52+ ]
53+ self.assertFalse(snap.db_need_init(connection))
54+
55+ def test_no_tables(self):
56+ connection = MagicMock()
57+ connection.introspection.table_names.return_value = []
58+ self.assertTrue(snap.db_need_init(connection))
59+
60+ def test_fail(self):
61+ connection = MagicMock()
62+ connection.introspection.table_names.side_effect = Exception(
63+ "connection failed"
64+ )
65+ self.assertTrue(snap.db_need_init(connection))

Subscribers

People subscribed via source and target branches