1
# -*- coding: utf-8 -*-
2
# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4
4
###############################################################################
5
# OpenLP - Open Source Lyrics Projection #
6
# --------------------------------------------------------------------------- #
7
# Copyright (c) 2008-2016 OpenLP Developers #
8
# --------------------------------------------------------------------------- #
9
# This program is free software; you can redistribute it and/or modify it #
10
# under the terms of the GNU General Public License as published by the Free #
11
# Software Foundation; version 2 of the License. #
13
# This program is distributed in the hope that it will be useful, but WITHOUT #
14
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
15
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
18
# You should have received a copy of the GNU General Public License along #
19
# with this program; if not, write to the Free Software Foundation, Inc., 59 #
20
# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
21
###############################################################################
23
The :mod:`db` module provides helper functions for database related methods.
28
from copy import deepcopy
30
log = logging.getLogger(__name__)
33
def drop_column(op, tablename, columnname):
34
drop_columns(op, tablename, [columnname])
37
def drop_columns(op, tablename, columns):
39
Column dropping functionality for SQLite, as there is no DROP COLUMN support in SQLite
41
From https://github.com/klugjohannes/alembic-sqlite
44
# get the db engine and reflect database tables
45
engine = op.get_bind()
46
meta = sqlalchemy.MetaData(bind=engine)
49
# create a select statement from the old table
50
old_table = meta.tables[tablename]
51
select = sqlalchemy.sql.select([c for c in old_table.c if c.name not in columns])
53
# get remaining columns without table attribute attached
54
remaining_columns = [deepcopy(c) for c in old_table.columns if c.name not in columns]
55
for column in remaining_columns:
58
# create a temporary new table
59
new_tablename = '{0}_new'.format(tablename)
60
op.create_table(new_tablename, *remaining_columns)
62
new_table = meta.tables[new_tablename]
64
# copy data from old table
65
insert = sqlalchemy.sql.insert(new_table).from_select([c.name for c in remaining_columns], select)
66
engine.execute(insert)
68
# drop the old table and rename the new table to take the old tables
70
op.drop_table(tablename)
71
op.rename_table(new_tablename, tablename)