aboutsummaryrefslogtreecommitdiff
path: root/src/gen_storage_migration.erl
blob: d965f7450886521f619d0f6c59d2cdb09843ff50 (plain) (blame)
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
-module(gen_storage_migration).

-export([migrate_mnesia/3, migrate_odbc/3]).

-include("ejabberd.hrl").

%% @spec (Host::storage_host(), Table::atom(), Migrations) -> any()
%% Migrations = [{OldTable, OldAttributes, MigrateFun}]
migrate_mnesia(Host, Table, Migrations) ->
    SameTableName = [Migration
		     || {OldTable, _, _} = Migration <- Migrations,
			OldTable =:= Table],
    lists:foreach(fun(Migration) ->
			  case (catch migrate_mnesia1(Host, Table, Migration)) of
			      ok -> ok;
			      ignored -> ok;
			      R ->
				  ?ERROR_MSG("Error performing migration ~p:~n~p",
					     [Migration, R])
			  end
		  end, SameTableName),
    DifferentTableName = [Migration
			  || {OldTable, _, _} = Migration <- Migrations,
			     OldTable =/= Table],
    lists:foreach(fun(Migration) ->
			  case (catch migrate_mnesia1(Host, Table, Migration)) of
			      ok -> ok;
			      ignored -> ok;
			      R ->
				  ?ERROR_MSG("Error performing migration ~p:~n~p",
					     [Migration, R])
			  end
		  end, DifferentTableName).

migrate_mnesia1(Host, Table, {OldTable, OldAttributes, MigrateFun}) ->
    HostB = list_to_binary(Host),
    case (catch mnesia:table_info(OldTable, attributes)) of
	OldAttributes ->
	    if
		Table =:= OldTable ->
		    %% TODO: move into transaction
		    TmpTable = list_to_atom(atom_to_list(Table) ++ "_tmp"),
		    NewRecordName = gen_storage:table_info(HostB, Table, record_name),
		    NewAttributes = gen_storage:table_info(HostB, Table, attributes),
		    ?INFO_MSG("Migrating mnesia table ~p via ~p~nfrom ~p~nto ~p",
			      [Table, TmpTable, OldAttributes, NewAttributes]),

		    {atomic, ok} = mnesia:create_table(
				     TmpTable,
				     [{disc_only_copies, [node()]},
				      {type, bag},
				      {local_content, true},
				      {record_name, NewRecordName},
				      {attributes, NewAttributes}]),
		    F1 = fun() ->
				 mnesia:write_lock_table(TmpTable),
				 mnesia:foldl(
				   fun(OldRecord, _) ->
					   NewRecord = MigrateFun(OldRecord),
					   ?DEBUG("~p-~p: ~p -> ~p~n",[OldTable, Table, OldRecord, NewRecord]),
					   if
					       is_tuple(NewRecord) ->
						   mnesia:write(TmpTable, NewRecord, write);
					       true ->
						   ignored
					   end
				   end, ok, OldTable)
			 end,
		    {atomic, ok} = mnesia:transaction(F1),
		    mnesia:delete_table(OldTable),
		    TableInfo = gen_storage:table_info(HostB, Table, all),
		    {value, {_, Backend}} = lists:keysearch(backend, 1, TableInfo),
		    gen_storage:create_table(Backend, HostB, Table, TableInfo),
		    F2 = fun() ->
				 mnesia:write_lock_table(Table),
				 mnesia:foldl(
				   fun(NewRecord, _) ->
					   ?DEBUG("~p-~p: ~p~n",[OldTable, Table, NewRecord]),
					   gen_storage:write(HostB, Table, NewRecord, write)
				   end, ok, TmpTable)
			 end,
		    {atomic, ok} = mnesia:transaction(F2),
		    mnesia:delete_table(TmpTable),
		    ?INFO_MSG("Migration of mnesia table ~p successfully finished", [Table]);

		Table =/= OldTable ->
		    ?INFO_MSG("Migrating mnesia table ~p to ~p~nfrom ~p",
			      [OldTable, Table, OldAttributes]),
		    F1 = fun() ->
				 mnesia:write_lock_table(Table),
				 mnesia:foldl(
				   fun(OldRecord, _) ->
					   NewRecord = MigrateFun(OldRecord),
					   ?DEBUG("~p-~p: ~p -> ~p~n",[OldTable, Table, OldRecord, NewRecord]),
					   if
					       is_tuple(NewRecord) ->
						   gen_storage:write(HostB, Table, NewRecord, write);
					       true ->
						   ignored
					   end
				   end, ok, OldTable)
			 end,
		    {atomic, _} = mnesia:transaction(F1),
		    mnesia:delete_table(OldTable),
		    ?INFO_MSG("Migration of mnesia table ~p successfully finished", [Table]),
		    ok
	    end;
	_ ->
	    ignored
    end.


migrate_odbc(Host, Tables, Migrations) ->
    try ejabberd_odbc:sql_transaction(
	  Host,
	  fun() ->
		  lists:foreach(
		    fun(Migration) ->
			    case (catch migrate_odbc1(Host, Tables, Migration)) of
				ok -> ok;
				ignored -> ok;
				R ->
				    ?ERROR_MSG("Error performing migration ~p:~n~p",
					       [Migration, R])
			    end
		    end, Migrations)
	  end)
    catch exit:{noproc, _Where} ->
	    ?INFO_MSG("Not migrating ODBC on host ~p because no ODBC was configured.", [Host]),
	    ok
    end.

migrate_odbc1(Host, Tables, {OldTable, OldColumns, MigrateFun}) ->
    migrate_odbc1(Host, Tables, {[{OldTable, OldColumns}], MigrateFun});

migrate_odbc1(Host, Tables, {OldTablesColumns, MigrateFun}) ->
    {[OldTable | _] = OldTables,
     [OldColumns | _] = OldColumnsAll} = lists:unzip(OldTablesColumns),
    OldTablesA = [list_to_atom(Table) || Table <- OldTables],
    ColumnsT = [odbc_table_columns_t(OldTable1) || OldTable1 <- OldTables],
    migrate_odbc2(Host, Tables, OldTable, OldTables, OldColumns, OldColumnsAll, OldTablesA, ColumnsT, MigrateFun).

migrate_odbc2(Host, Tables, OldTable, OldTables, OldColumns, OldColumnsAll, OldTablesA, ColumnsT, MigrateFun)
  when ColumnsT == OldColumnsAll ->
    ?INFO_MSG("Migrating ODBC table ~p to gen_storage tables ~p", [OldTable, Tables]),
    HostB = list_to_binary(Host),

    %% rename old tables to *_old
    lists:foreach(fun(OldTable1) ->
			  {updated, _} =
			      ejabberd_odbc:sql_query_t("alter table " ++ OldTable1 ++
							    " rename to " ++ OldTable1 ++ "_old")
		  end, OldTables),
    %% recreate new tables
    lists:foreach(fun(NewTable) ->
			  case lists:member(NewTable, OldTablesA) of
			      true ->
				  TableInfo =
				      gen_storage:table_info(HostB, NewTable, all),
				  {value, {_, Backend}} =
				      lists:keysearch(backend, 1, TableInfo),
				  gen_storage:create_table(Backend, HostB,
							   NewTable, TableInfo);
			      false -> ignored
			  end
		  end, Tables),

    SELECT =
	fun(Columns, Table, Keys) ->
		Table1 = case lists:member(Table, OldTables) of
			     true -> Table ++ "_old";
			     false -> Table
			 end,
		WherePart = case Keys of
				[] -> "";
				_ -> " WHERE " ++
					 string:join([K ++ "=" ++
							  if
							      is_list(V) ->
								  "\"" ++ ejabberd_odbc:escape(V) ++ "\"";
							      is_integer(V) ->
								  integer_to_list(V)
							  end
						      || {K, V} <- Keys],
						     " AND ")
			    end,
		{selected, _, Rows} =
		    ejabberd_odbc:sql_query_t("SELECT " ++ string:join(Columns, ", ") ++
						  " FROM " ++ Table1 ++
						  WherePart),
		[tuple_to_list(Row) || Row <- Rows]
	end,

    %% TODO: this will need lots of RAM, make it batched
    OldRows = SELECT(OldColumns, OldTable, []),
    NRows =
	lists:foldl(fun(OldRow, NRow) ->
			    NewRecords = apply(MigrateFun, [SELECT | OldRow]),
			    if
				is_list(NewRecords) ->
				    lists:foreach(
				      fun(NewRecord) ->
					      %% TODO: gen_storage transaction?
					      gen_storage:dirty_write(HostB, NewRecord)
				      end, NewRecords);
				is_tuple(NewRecords) ->
				    gen_storage:dirty_write(HostB, NewRecords)
			    end,
			    NRow + 1
		    end, 0, OldRows),

    lists:foreach(fun(OldTable1) ->
			  {updated, _} = ejabberd_odbc:sql_query_t("drop table " ++ OldTable1 ++ "_old")
		  end, OldTables),

    ?INFO_MSG("Migrated ODBC table ~p to gen_storage tables ~p (~p rows)", [OldTable, Tables, NRows]),
    ok;

migrate_odbc2(_Host, _Tables, _OldTable, _OldTables, _OldColumns, _OldColumnsAll, _OldTablesA, [[]], _MigrateFun) ->
    ignored;

migrate_odbc2(Host, Tables, OldTable, OldTables, OldColumns, OldColumnsAll, OldTablesA, [ColumnsTAndCreatedat | MoreCTAC], MigrateFun)
  when ColumnsTAndCreatedat /= OldColumnsAll ->
    case lists:last(ColumnsTAndCreatedat) of
	"created_at" ->
	    ColumnsT = ColumnsTAndCreatedat -- ["created_at"],
	    migrate_odbc2(Host, Tables, OldTable, OldTables, OldColumns, OldColumnsAll, OldTablesA, [ColumnsT | MoreCTAC], MigrateFun);
        _ ->
	    ignored
    end.

odbc_table_columns_t(Table) ->
    case ejabberd_odbc:sql_query_t("select column_name from information_schema.columns where table_name='" ++ Table ++ "'") of
	{selected, _, Columns1} ->
	    Columns2 = lists:map(fun({C}) -> C end, Columns1),
	    Columns2
    end.