Browse Source

add command to delete database, usefull for testing

Guénaël Muller 7 years ago
parent
commit
9a8658bfbe
4 changed files with 67 additions and 7 deletions
  1. 11 1
      doc/cli.md
  2. 2 1
      setup.py
  3. 53 4
      tracim/command/database.py
  4. 1 1
      tracim/tests/__init__.py

+ 11 - 1
doc/cli.md View File

16
 
16
 
17
 ### Create database
17
 ### Create database
18
 
18
 
19
-    tracim db init
19
+    tracimcli db init
20
+
21
+### Create database with some default test data (many users, workspaces, etc…)
22
+
23
+    tracimcli db init --test-data
24
+
25
+### Delete database /!\
26
+
27
+This will drop all your database, be carefull !
28
+
29
+    tracimcli db delete --force
20
 
30
 
21
 ## User ##
31
 ## User ##
22
    
32
    

+ 2 - 1
setup.py View File

98
             'test = tracim.command:TestTracimCommand',
98
             'test = tracim.command:TestTracimCommand',
99
             'user_create = tracim.command.user:CreateUserCommand',
99
             'user_create = tracim.command.user:CreateUserCommand',
100
             'user_update = tracim.command.user:UpdateUserCommand',
100
             'user_update = tracim.command.user:UpdateUserCommand',
101
-            'db_init = tracim.command.initializedb:InitializeDBCommand',
101
+            'db_init = tracim.command.database:InitializeDBCommand',
102
+            'db_delete = tracim.command.database:DeleteDBCommand',
102
             'webdav start = tracim.command.webdav:WebdavRunnerCommand',
103
             'webdav start = tracim.command.webdav:WebdavRunnerCommand',
103
         ]
104
         ]
104
     },
105
     },

tracim/command/initializedb.py → tracim/command/database.py View File

11
 from tracim import CFG
11
 from tracim import CFG
12
 from tracim.fixtures import FixturesLoader
12
 from tracim.fixtures import FixturesLoader
13
 from tracim.fixtures.users_and_groups import Base as BaseFixture
13
 from tracim.fixtures.users_and_groups import Base as BaseFixture
14
+from tracim.fixtures.content import Content as ContentFixture
14
 from sqlalchemy.exc import IntegrityError
15
 from sqlalchemy.exc import IntegrityError
15
 from tracim.command import AppContextCommand
16
 from tracim.command import AppContextCommand
16
 from tracim.models.meta import DeclarativeBase
17
 from tracim.models.meta import DeclarativeBase
25
     auto_setup_context = False
26
     auto_setup_context = False
26
 
27
 
27
     def get_description(self) -> str:
28
     def get_description(self) -> str:
28
-        return "Initialize DB"
29
+        return "Initialize database"
29
 
30
 
30
     def get_parser(self, prog_name: str) -> argparse.ArgumentParser:
31
     def get_parser(self, prog_name: str) -> argparse.ArgumentParser:
31
         parser = super().get_parser(prog_name)
32
         parser = super().get_parser(prog_name)
33
+        parser.add_argument(
34
+            "--test-data",
35
+            help='Add some default data to database to make test',
36
+            dest='test_data',
37
+            required=False,
38
+            action='store_true',
39
+            default=False,
40
+        )
32
         return parser
41
         return parser
33
 
42
 
34
     def take_action(self, parsed_args: argparse.Namespace) -> None:
43
     def take_action(self, parsed_args: argparse.Namespace) -> None:
37
         setup_logging(config_uri)
46
         setup_logging(config_uri)
38
         settings = get_appsettings(config_uri)
47
         settings = get_appsettings(config_uri)
39
         self._create_schema(settings)
48
         self._create_schema(settings)
40
-        self._populate_database(settings)
49
+        self._populate_database(settings, add_test_data=parsed_args.test_data)
41
 
50
 
42
     @classmethod
51
     @classmethod
43
     def _create_schema(
52
     def _create_schema(
51
     @classmethod
60
     @classmethod
52
     def _populate_database(
61
     def _populate_database(
53
             cls,
62
             cls,
54
-            settings: plaster_pastedeploy.ConfigDict
63
+            settings: plaster_pastedeploy.ConfigDict,
64
+            add_test_data: bool
55
     ) -> None:
65
     ) -> None:
56
         engine = get_engine(settings)
66
         engine = get_engine(settings)
57
         session_factory = get_session_factory(engine)
67
         session_factory = get_session_factory(engine)
60
         with transaction.manager:
70
         with transaction.manager:
61
             dbsession = get_tm_session(session_factory, transaction.manager)
71
             dbsession = get_tm_session(session_factory, transaction.manager)
62
             try:
72
             try:
73
+                fixtures = [BaseFixture]
63
                 fixtures_loader = FixturesLoader(dbsession, app_config)
74
                 fixtures_loader = FixturesLoader(dbsession, app_config)
64
-                fixtures_loader.loads([BaseFixture])
75
+                fixtures_loader.loads(fixtures)
76
+                transaction.commit()
77
+                if add_test_data:
78
+                    app_config.configure_filedepot()
79
+                    fixtures = [ContentFixture]
80
+                    fixtures_loader.loads(fixtures)
65
                 transaction.commit()
81
                 transaction.commit()
66
                 print("Database initialized.")
82
                 print("Database initialized.")
67
             except IntegrityError:
83
             except IntegrityError:
71
                 print(traceback.format_exc())
87
                 print(traceback.format_exc())
72
                 transaction.abort()
88
                 transaction.abort()
73
                 print('Database initialization failed')
89
                 print('Database initialization failed')
90
+
91
+
92
+class DeleteDBCommand(AppContextCommand):
93
+    auto_setup_context = False
94
+
95
+    def get_description(self) -> str:
96
+        return "Delete database"
97
+
98
+    def get_parser(self, prog_name: str) -> argparse.ArgumentParser:
99
+        parser = super().get_parser(prog_name)
100
+        parser.add_argument(
101
+            "--force",
102
+            help='force delete of database',
103
+            dest='force',
104
+            required=False,
105
+            action='store_true',
106
+            default=False,
107
+        )
108
+        return parser
109
+
110
+    def take_action(self, parsed_args: argparse.Namespace) -> None:
111
+        super(DeleteDBCommand, self).take_action(parsed_args)
112
+        config_uri = parsed_args.config_file
113
+        setup_logging(config_uri)
114
+        settings = get_appsettings(config_uri)
115
+        engine = get_engine(settings)
116
+        if parsed_args.force:
117
+            print('Database deletion begin')
118
+            DeclarativeBase.metadata.drop_all(engine)
119
+            print('Database deletion done')
120
+        else:
121
+            print('Warning, You should use --force if you really want to'
122
+                  ' delete database.')

+ 1 - 1
tracim/tests/__init__.py View File

5
 from pyramid import testing
5
 from pyramid import testing
6
 from sqlalchemy.exc import IntegrityError
6
 from sqlalchemy.exc import IntegrityError
7
 
7
 
8
-from tracim.command.initializedb import InitializeDBCommand
8
+from tracim.command.database import InitializeDBCommand
9
 from tracim.lib.core.content import ContentApi
9
 from tracim.lib.core.content import ContentApi
10
 from tracim.lib.core.workspace import WorkspaceApi
10
 from tracim.lib.core.workspace import WorkspaceApi
11
 from tracim.models import get_engine, DeclarativeBase, get_session_factory, \
11
 from tracim.models import get_engine, DeclarativeBase, get_session_factory, \