chiark / gitweb /
httpauth.py: Improve the CSRF token stuff.
[chopwood] / dbmaint.py
CommitLineData
a2916c06
MW
1### -*-python-*-
2###
3### Database maintenance
4###
5### (c) 2013 Mark Wooding
6###
7
8###----- Licensing notice ---------------------------------------------------
9###
10### This file is part of Chopwood: a password-changing service.
11###
12### Chopwood is free software; you can redistribute it and/or modify
13### it under the terms of the GNU Affero General Public License as
14### published by the Free Software Foundation; either version 3 of the
15### License, or (at your option) any later version.
16###
17### Chopwood is distributed in the hope that it will be useful,
18### but WITHOUT ANY WARRANTY; without even the implied warranty of
19### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20### GNU Affero General Public License for more details.
21###
22### You should have received a copy of the GNU Affero General Public
23### License along with Chopwood; if not, see
24### <http://www.gnu.org/licenses/>.
25
26from __future__ import with_statement
27
28import config as CONF; CFG = CONF.CFG
29import subcommand as SC
30import util as U
31
32###--------------------------------------------------------------------------
33### Opening the database.
34
35## Current database schema version.
36DB_VERSION = 0
37
38def opendb():
39 """Open connections to the master database, updating it if necessary."""
40
41 global DB
42
43 ## Open the database.
44 dbmod, dbargs = CFG.DB
45 DB = U.SimpleDBConnection(dbmod, dbargs)
46
47 ## Find out the current version.
48 try:
49 DB.execute("SELECT version FROM meta")
50 except DB.Error:
51 ver = 0
52 else:
53 ver, = DB.fetchone()
54 if ver > DB_VERSION:
55 raise ExpectedError, (500, "Database schema version not understood.")
56
57 ## In future, there will be an attempt to upgrade databases with old
58 ## schemata to the current version. But not yet.
59 pass
60
61###--------------------------------------------------------------------------
62### Database setup.
63
64@SC.subcommand('setup', ['admin'], 'Initialize the master database.')
65def cmd_setup():
66 script = """
67 CREATE TABLE users (
68 user VARCHAR(32) PRIMARY KEY NOT NULL,
69 passwd TEXT NOT NULL DEFAULT('*'),
70 email TEXT);
71 CREATE TABLE services (
72 user VARCHAR(32) NOT NULL,
73 service VARCHAR(32) NOT NULL,
74 alias VARCHAR(32),
75 PRIMARY KEY (user, service),
76 FOREIGN KEY (user) REFERENCES users(user)
77 ON UPDATE CASCADE
78 ON DELETE CASCADE);
79 CREATE TABLE meta (
80 version INTEGER NOT NULL);
81 CREATE TABLE secrets (
82 stamp INTEGER PRIMARY KEY NOT NULL,
83 secret TEXT NOT NULL);
84 """
85 with DB:
86 for cmd in script.split(';'):
87 if not cmd.isspace():
88 DB.execute(cmd)
89 DB.execute("INSERT INTO meta(version) VALUES ($version)",
90 version = DB_VERSION)
91
92###----- That's all, folks --------------------------------------------------