BootstrapBean.java 22.6 KB
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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
/*
 * Copyright Codecrew Ry
 *
 * All rights reserved.
 *
 * This license applies to any software containing a notice placed by the
 * copyright holder. Such software is herein referred to as the Software.
 * This license covers modification, distribution and use of the Software.
 *
 * Any distribution and use in source and binary forms, with or without
 * modification is not permitted without explicit written permission from the
 * copyright owner.
 *
 * A non-exclusive royalty-free right is granted to the copyright owner of the
 * Software to use, modify and distribute all modifications to the Software in
 * future versions of the Software.
 *
 */
package fi.codecrew.moya.beans;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.ejb.Startup;

import fi.codecrew.moya.facade.DBModelFacade;
import fi.codecrew.moya.facade.UserFacade;
import fi.codecrew.moya.model.DBModel;
import fi.codecrew.moya.sql.DDLBuilder;

@Singleton
@Startup
public class BootstrapBean implements BootstrapBeanLocal {

	@EJB
	UserFacade userFacade;

	@EJB
	private DBModelFacade dbModelFacade;

	private static final List<String[]> dbUpdates = new ArrayList<String[]>();

	static {
		// {"Query1","Query2",...}
		dbUpdates.add(new String[]{""}); // first version, no changes
		dbUpdates.add(new String[]{"ALTER TABLE tournaments ADD COLUMN game integer NOT NULL REFERENCES tournament_games(id)"});
		dbUpdates.add(new String[]{"ALTER TABLE tournaments ADD COLUMN rules integer NOT NULL REFERENCES tournament_rules(id)"});
		dbUpdates.add(new String[]{"ALTER TABLE tournaments ADD COLUMN max_participants integer NOT NULL DEFAULT 0"});
		dbUpdates.add(new String[]{"ALTER TABLE tournament_participants ADD COLUMN tournament integer NOT NULL REFERENCES tournaments(id)"});
		dbUpdates.add(new String[]{"DELETE FROM application_permissions WHERE application = 'MAP' and permission = 'RELEASE_PLACE'"});
		dbUpdates.add(new String[]{"ALTER TABLE site_page_content ADD COLUMN locale varchar(10)"});
		dbUpdates.add(new String[]{"ALTER TABLE products ALTER COLUMN vat TYPE NUMERIC(4,3)"});
		dbUpdates.add(new String[]{"ALTER TABLE actionlog_messages DROP COLUMN crew"});
		dbUpdates.add(new String[]{"delete from application_permissions where application ilike '%terminal%'"});
		dbUpdates.add(new String[]{
				"ALTER TABLE org_roles ADD ldap_role boolean not null default false",
				"ALTER TABLE org_roles ADD ldap_weight integer NOT NULL default 100"
		});
		// barcodefuckup
		dbUpdates.add(new String[]{
				"DROP TABLE card_barcode",
				"ALTER TABLE printed_cards DROP COLUMN barcode;",
				"ALTER TABLE printed_cards DROP COLUMN rfid_uid;",
				"ALTER TABLE reader_events ADD COLUMN event_users_id integer REFERENCES event_users(id) DEFAULT null;",
				"ALTER TABLE reader_events ADD COLUMN places_id integer REFERENCES places(id) DEFAULT null;",
				"ALTER TABLE reader_events ADD COLUMN products_id integer REFERENCES products(id) DEFAULT null;",
				"ALTER TABLE reader_events ADD COLUMN type text NOT NULL DEFAULT 'UNKNOWN';",
				"ALTER TABLE reader_events DROP COLUMN gamepoint;",
				"ALTER TABLE reader_events ALTER COLUMN type DROP DEFAULT;",
		});

		dbUpdates.add(new String[]{
				"delete from menu_navigation where item_id in (select id from menuitem where url in ( '/actionlog/messagelist'))",
				"delete from menuitem where url in ('/actionlog/messagelist')",
		});
		dbUpdates.add(new String[]{
				"alter table compos add hidden boolean default false not null"
		});

		dbUpdates.add(alterTables("ADD COLUMN meta json",
				"account_events",
				"actionlog_message_responses",
				"actionlog_message_tags",
				"actionlog_messages",
				"api_application_instances",
				"api_applications",
				"application_permissions",
				"approvals",
				"bill_lines",
				"bills",
				"card_code",
				"card_templates",
				"compo_entries",
				"compo_entry_files",
				"compo_entry_participations",
				"compo_votes",
				"compos",
				"discount_instances",
				"discounts",
				"event_domains",
				"event_log",
				"event_log_types",
				"event_organiser",
				"event_private_properties",
				"event_properties",
				"event_users",
				"events",
				"feedback",
				"food_wave_templates",
				"food_waves",
				"game_ids",
				"group_memberships",
				"groups",
				"inventory_events",
				"licensetargets",
				"licensecodes",
				"locations",
				"maps",
				"match_results",
				"matches",
				"menu_navigation",
				"menuitem",
				"news",
				"news_groups",
				"org_roles",
				"places",
				"poll",
				"poll_answer",
				"poll_question",
				"possible_answer",
				"printed_cards",
				"product_limitations",
				"products",
				"reader_events",
				"readers",
				"roles",
				"sales_entity",
				"salespoint",
				"site_page_content",
				"site_pages",
				"tournament_games",
				"tournament_participants",
				"tournament_rules",
				"tournament_team_members",
				"tournaments",
				"user_approvals",
				"user_images",
				"user_notes",
				"users"));

		dbUpdates.add(new String[]{"CREATE TABLE network_associations (id  SERIAL NOT NULL, create_time TIMESTAMPTZ NOT NULL, ip TEXT, mac TEXT, meta TEXT, modify_time TIMESTAMPTZ NOT NULL, status TEXT NOT NULL, event INTEGER, event_user INTEGER, place INTEGER, PRIMARY KEY (id))"});

		dbUpdates.add(new String[]{
				"CREATE TABLE card_text_data (id  SERIAL NOT NULL, font_name TEXT NOT NULL, font_style INTEGER NOT NULL, size INTEGER NOT NULL, text TEXT, text_alignment TEXT NOT NULL, card_text_data_type TEXT NOT NULL, x INTEGER NOT NULL, y INTEGER NOT NULL, z_index INTEGER NOT NULL, PRIMARY KEY (id));"
		});
		dbUpdates.add(new String[]{
				"CREATE TABLE card_object_data (id  SERIAL NOT NULL, card_object_data_type TEXT NOT NULL, size INTEGER NOT NULL, x INTEGER NOT NULL, y INTEGER NOT NULL, z_index INTEGER NOT NULL, PRIMARY KEY (id));"
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE card_text_data ADD COLUMN card_templates_id integer REFERENCES card_templates(id) DEFAULT null;",
				"ALTER TABLE card_object_data ADD COLUMN card_templates_id integer REFERENCES card_templates(id) DEFAULT null;"
		});

		dbUpdates.add(alterTables("ADD COLUMN meta json",
				"card_text_data",
				"card_object_data"));
		dbUpdates.add(new String[]{
				"ALTER TABLE card_text_data ADD COLUMN font_color_r integer DEFAULT 0;",
				"ALTER TABLE card_text_data ADD COLUMN font_color_g integer DEFAULT 0;",
				"ALTER TABLE card_text_data ADD COLUMN font_color_b integer DEFAULT 0;"
		});
		dbUpdates.add(new String[]{
				"ALTER TABLE card_text_data ALTER COLUMN size TYPE numeric(5,2);",
				"ALTER TABLE card_object_data ALTER COLUMN size TYPE numeric(5,2);"
		});
		dbUpdates.add(new String[]{
				"ALTER TABLE card_text_data DROP COLUMN font_style;",
				"ALTER TABLE card_text_data ADD COLUMN font_style TEXT NOT NULL DEFAULT 'PLAIN';"
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE event_log RENAME log_id TO id;"
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE network_associations ALTER COLUMN meta TYPE json USING (meta::json);"
		});

		dbUpdates.add(new String[]{"CREATE TABLE lecture_groups (id  SERIAL NOT NULL, event_id integer NOT NULL,  description TEXT, name TEXT,  select_count INTEGER, meta json, PRIMARY KEY (id))",
				"CREATE TABLE lectures (id  SERIAL NOT NULL, description TEXT, hours numeric(10,2), max_participants_count INTEGER, name TEXT, start_time TIMESTAMPTZ, lecture_group_id INTEGER, meta json, PRIMARY KEY (id))",
				"CREATE TABLE lecture_roles (role_id INTEGER NOT NULL, lecture_id INTEGER NOT NULL, PRIMARY KEY (role_id, lecture_id))",
				"CREATE TABLE lecture_participants (eventuser_id INTEGER NOT NULL, lecture_id INTEGER NOT NULL, PRIMARY KEY (eventuser_id, lecture_id))",
				"ALTER TABLE lectures ADD CONSTRAINT FK_lectures_lecture_group_id FOREIGN KEY (lecture_group_id) REFERENCES lecture_groups (id)",
				"ALTER TABLE lecture_roles ADD CONSTRAINT FK_lecture_roles_lecture_id FOREIGN KEY (lecture_id) REFERENCES lectures (id)",
				"ALTER TABLE lecture_roles ADD CONSTRAINT FK_lecture_roles_role_id FOREIGN KEY (role_id) REFERENCES roles (id)",
				"ALTER TABLE lecture_participants ADD CONSTRAINT FK_lecture_participants_eventuser_id FOREIGN KEY (eventuser_id) REFERENCES event_users (id)",
				"ALTER TABLE lecture_participants ADD CONSTRAINT FK_lecture_participants_lecture_id FOREIGN KEY (lecture_id) REFERENCES lectures (id)"});

		dbUpdates.add(new String[]{"ALTER TABLE roles ADD COLUMN user_selectable_role boolean DEFAULT false;"});

		dbUpdates.add(new String[]{
				"ALTER TABLE group_memberships ADD COLUMN place_product INTEGER",
				"ALTER TABLE group_memberships ADD CONSTRAINT FK_group_memberships_place_product FOREIGN KEY (place_product) REFERENCES products (id)"
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE events ADD COLUMN ticket_sales_begin timestamp without time zone DEFAULT null;",
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE events ADD COLUMN theme varchar(255) DEFAULT null;",
		});

		// Deprekoidaan ko. enum, jolloin se pitää myös poistaa tietokannasta
		// tai saadaan poikkeuksia nyrkillä kurkusta .
		dbUpdates.add(new String[]{
				"DELETE FROM  product_productflags where productflags = 'PREPAID_INSTANT_CREATE'"
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE food_wave_templates ADD COLUMN wait_payments_minutes integer DEFAULT null;",
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE maps ADD COLUMN width integer",
				"ALTER TABLE maps ADD COLUMN height integer",
		});

		dbUpdates.add(new String[]{
				"CREATE TABLE place_slots (id SERIAL NOT NULL, CREATED TIMESTAMPTZ, DESCRIPTION TEXT, meta json, USED TIMESTAMPTZ, BILL_id INTEGER NOT NULL, PRODUCT_id INTEGER NOT NULL, PLACE_id INTEGER UNIQUE, PRIMARY KEY (id))",
				"ALTER TABLE place_slots ADD CONSTRAINT FK_place_slots_BILL_id FOREIGN KEY (BILL_id) REFERENCES bills (id)",
				"ALTER TABLE place_slots ADD CONSTRAINT FK_place_slots_PLACE_id FOREIGN KEY (PLACE_id) REFERENCES places (id)",
				"ALTER TABLE place_slots ADD CONSTRAINT FK_place_slots_PRODUCT_id FOREIGN KEY (PRODUCT_id) REFERENCES products (id)"
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE maps ADD COLUMN mime_type TEXT default 'image/png'",
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE group_memberships ADD COLUMN entered_event_admin_id INTEGER",
				"ALTER TABLE group_memberships ADD CONSTRAINT FK_group_memberships_entered_event_admin_id FOREIGN KEY (entered_event_admin_id) REFERENCES event_users (id)",
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE group_memberships DROP COLUMN place_product",
		});

		dbUpdates.add(new String[]{
				"DELETE FROM product_limitations_roles where productlimitation_id in (SELECT id FROM product_limitations WHERE TYPE = 'PLACE')",
				"DELETE FROM products_product_limitations where productlimits_id in (SELECT id FROM product_limitations WHERE TYPE = 'PLACE')",
				"DELETE FROM product_limitations WHERE TYPE = 'PLACE'",

		});

		dbUpdates.add(new String[]{
				new DDLBuilder().createTable("vips")
						.serialPK("id")
						.text("description", false)
						.timestampTZ("created", false, "default", "now()")
						.reference("event_id", false, "events")
						.reference("vip_event_user_id", true, "event_users")
						.reference("creator_event_user_id", false, "event_users")
						.reference("host_event_user_id", false, "event_users")
						.field("meta", "json", true)
						.toString()
		});

		dbUpdates.add(new String[]{
				"CREATE TABLE vip_product_deliveries (id SERIAL NOT NULL, DELIVERYTIME TIMESTAMPTZ NOT NULL, meta json, NOTES TEXT, quantity DECIMAL(24,4) NOT NULL, DELIVERER_id INTEGER NOT NULL, VIPPRODUCT_id INTEGER NOT NULL, PRIMARY KEY (id))",
				"CREATE TABLE vip_products (id SERIAL NOT NULL, meta json, NAME TEXT, NOTES TEXT, quantity DECIMAL(24,4) NOT NULL, PRODUCT_id INTEGER, VIP_id INTEGER NOT NULL, PRIMARY KEY (id))",
				"ALTER TABLE vip_product_deliveries ADD CONSTRAINT FK_vip_product_deliveries_DELIVERER_id FOREIGN KEY (DELIVERER_id) REFERENCES event_users (id)",
				"ALTER TABLE vip_product_deliveries ADD CONSTRAINT FK_vip_product_deliveries_VIPPRODUCT_id FOREIGN KEY (VIPPRODUCT_id) REFERENCES vip_products (id)",
				"ALTER TABLE vip_products ADD CONSTRAINT FK_vip_products_PRODUCT_id FOREIGN KEY (PRODUCT_id) REFERENCES products (id)",
				"ALTER TABLE vip_products ADD CONSTRAINT FK_vip_products_VIP_id FOREIGN KEY (VIP_id) REFERENCES vips (id)",
				"ALTER TABLE vips ADD shortdescr TEXT"
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE products ADD shop_required_role INTEGER",
				"ALTER TABLE products ADD CONSTRAINT FK_products_shop_required_role FOREIGN KEY (shop_required_role) REFERENCES roles (id)",
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE org_roles ADD user_requestable BOOLEAN NOT NULL DEFAULT FALSE",
				"ALTER TABLE org_roles ADD notes TEXT",
		});

		dbUpdates.add(new String[]{
				"CREATE TABLE org_role_requests (id INTEGER NOT NULL, handled_notes TEXT, meta json, request_date TIMESTAMPTZ NOT NULL, requeste_handled TIMESTAMPTZ, request_notes TEXT, handler_id INTEGER NOT NULL, requested_role INTEGER NOT NULL, user_id INTEGER NOT NULL, PRIMARY KEY (id))",
				"ALTER TABLE org_role_requests ADD CONSTRAINT FK_org_role_requests_handler_id FOREIGN KEY (handler_id) REFERENCES users (id)",
				"ALTER TABLE org_role_requests ADD CONSTRAINT FK_org_role_requests_requested_role FOREIGN KEY (requested_role) REFERENCES org_roles (id)",
				"ALTER TABLE org_role_requests ADD CONSTRAINT FK_org_role_requests_user_id FOREIGN KEY (user_id) REFERENCES users (id)",
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE events ADD codecrew_responsible_user_id INTEGER",
				"ALTER TABLE events ADD CONSTRAINT FK_events_codecrew_responsible_users FOREIGN KEY (codecrew_responsible_user_id) REFERENCES users (id)",
				"ALTER TABLE events ADD organiser_responsible_user_id INTEGER",
				"ALTER TABLE events ADD CONSTRAINT FK_events_organiser_responsible_users FOREIGN KEY (organiser_responsible_user_id) REFERENCES users (id)",
				"ALTER TABLE events ADD codecrew_notes TEXT",
		});

		dbUpdates.add(new String[]{
				"update events set end_time = '2010-01-01 00:00:00' where end_time is null"
		});

		// ... jepjep.. Lefu
		dbUpdates.add(new String[]{
				"DROP TABLE org_role_requests",
				"CREATE TABLE org_role_requests (id SERIAL NOT NULL, handled_notes TEXT, meta json, request_date TIMESTAMPTZ NOT NULL, requeste_handled TIMESTAMPTZ, request_notes TEXT, handler_id INTEGER, requested_role INTEGER NOT NULL, user_id INTEGER NOT NULL, PRIMARY KEY (id))",
				"ALTER TABLE org_role_requests ADD CONSTRAINT FK_org_role_requests_handler_id FOREIGN KEY (handler_id) REFERENCES users (id)",
				"ALTER TABLE org_role_requests ADD CONSTRAINT FK_org_role_requests_requested_role FOREIGN KEY (requested_role) REFERENCES org_roles (id)",
				"ALTER TABLE org_role_requests ADD CONSTRAINT FK_org_role_requests_user_id FOREIGN KEY (user_id) REFERENCES users (id)",
		});

		// Run some profiling against local database. These were few of the low hanging fruits.
		dbUpdates.add(new String[]{
				// User searching in admin view (seq scan to index scan)
				"CREATE INDEX idx_eventuser_event ON event_users (event_id)",
				// Menu subpage parent search.
				"CREATE INDEX idx_menu_navigation_parent ON menu_navigation (parent_id)",
				// constraint domains case insensitive also at database level.
				// Select does not hit this yet because table is so small, but might someday
				"CREATE UNIQUE INDEX idx_event_domains_domainname_key_lower ON event_domains (LOWER(domainname))",
				// used for placecount calculation in shopping
				"CREATE INDEX idx_places_product_id ON places (products_id)",
				// Used placeslots calculation in shopping
				"CREATE INDEX idx_place_slots_products ON place_slots (product_id, place_id)",
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE event_users ADD tokencode text"
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE event_users ADD UNIQUE (tokencode)"
		});

		deleteMenu("/useradmin/changePassword");

		dbUpdates.add(new String[]{
				"CREATE TABLE helps (id SERIAL NOT NULL, path TEXT, meta json, PRIMARY KEY (id))",

				"CREATE TABLE help_texts (id SERIAL NOT NULL, " +
						"title TEXT, " +
						"description TEXT, " +
						"locale TEXT, " +
						"meta json, " +
						"last_edit_time TIMESTAMPTZ NOT NULL, " +
						"users_id INTEGER NOT NULL, " +
						"helps_id INTEGER NOT NULL, " +
						"PRIMARY KEY (id))",
				"ALTER TABLE help_texts " +
						"ADD CONSTRAINT FK_help_texts_users_id " +
						"FOREIGN KEY (users_id) REFERENCES users (id)",
				"ALTER TABLE help_texts " +
						"ADD CONSTRAINT FK_help_texts_helps_id " +
						"FOREIGN KEY (helps_id) REFERENCES helps (id)",

				"CREATE TABLE help_text_histories (id SERIAL NOT NULL, " +
						"title TEXT, " +
						"description TEXT, " +
						"meta json, " +
						"edit_time TIMESTAMPTZ NOT NULL, " +
						"help_texts_id INTEGER NOT NULL, " +
						"users_id INTEGER NOT NULL, " +
						"PRIMARY KEY (id))",
				"ALTER TABLE help_text_histories " +
						"ADD CONSTRAINT FK_help_text_histories_help_texts_id " +
						"FOREIGN KEY (help_texts_id) REFERENCES help_texts (id)",

		});

		dbUpdates.add(new String[]{
				"ALTER TABLE help_texts DROP COLUMN users_id;",
				"ALTER TABLE help_texts ADD COLUMN event_users_id  INTEGER NOT NULL;",
				"ALTER TABLE help_text_histories DROP COLUMN users_id;",
				"ALTER TABLE help_text_histories ADD COLUMN event_users_id  INTEGER NOT NULL;",

				"ALTER TABLE help_texts " +
						"ADD CONSTRAINT FK_help_texts_event_users_id " +
						"FOREIGN KEY (event_users_id) REFERENCES event_users (id)",
				"ALTER TABLE help_text_histories " +
						"ADD CONSTRAINT FK_help_text_histories_event_users_id " +
						"FOREIGN KEY (event_users_id) REFERENCES event_users (id)",

		});


		// we do rename magic, so we do not lose reserve -information. We don't really care about this time maybe being 1hour offsync
		dbUpdates.add(new String[]{
				"ALTER TABLE places RENAME release_time  TO reserve_time;"
		});

		dbUpdates.add(new String[]{
				"CREATE TABLE tournament_roles (role_id INTEGER NOT NULL, tournament_id INTEGER NOT NULL, PRIMARY KEY (role_id, tournament_id))",
				"ALTER TABLE tournament_roles ADD CONSTRAINT FK_tournament_roles_tournament_id FOREIGN KEY (tournament_id) REFERENCES tournaments (id)",
				"ALTER TABLE tournament_roles ADD CONSTRAINT FK_tournament_roles_role_id FOREIGN KEY (role_id) REFERENCES roles (id)",
		});

		dbUpdates.add(new String[]{
				"CREATE TABLE product_option_groups (id SERIAL NOT NULL, meta json, name TEXT, required BOOLEAN NOT NULL, default_product_option_id INTEGER, product_id INTEGER NOT NULL, PRIMARY KEY (id))",
				"CREATE TABLE product_options (id SERIAL NOT NULL, meta json, name TEXT, priority INTEGER, price_change INTEGER, product_option_group_id INTEGER NOT NULL, PRIMARY KEY (id))",
				"ALTER TABLE product_option_groups ADD CONSTRAINT FK_product_option_groups_default_product_option_id FOREIGN KEY (default_product_option_id) REFERENCES product_options (id)",
				"ALTER TABLE product_option_groups ADD CONSTRAINT FK_product_option_groups_product_id FOREIGN KEY (product_id) REFERENCES products (id)",
				"ALTER TABLE product_options ADD CONSTRAINT FK_product_options_product_option_group_id FOREIGN KEY (product_option_group_id) REFERENCES product_option_groups (id)",


		});

		dbUpdates.add(new String[]{
				"ALTER TABLE products ADD COLUMN min_buy_count INTEGER default 0;"
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE discounts ADD COLUMN sort INTEGER NOT NULL default 10;"
		});


		dbUpdates.add(new String[]{
				"CREATE TABLE map_queue_rules (id SERIAL NOT NULL, meta json, reserving_size INTEGER, default_timeout_min INTEGER, minium_slots_in_queue INTEGER, map_id INTEGER NOT NULL , PRIMARY KEY (id))",
				"ALTER TABLE map_queue_rules ADD CONSTRAINT FK_map_queue_rules_map_id FOREIGN KEY (map_id) REFERENCES maps (id)",
		});

		dbUpdates.add(new String[]{
				"ALTER TABLE map_queue_rules ADD COLUMN biggest_first BOOLEAN default false",
		});

		dbUpdates.add(new String[]{
				"CREATE TABLE product_dependencies (id SERIAL NOT NULL, dependency_type TEXT NOT NULL, meta json, multiplier DECIMAL(24,6) NOT NULL, priority INTEGER NOT NULL, dependant_id INTEGER NOT NULL, supporter_id INTEGER NOT NULL, PRIMARY KEY (id))",
				"ALTER TABLE product_dependencies ADD CONSTRAINT FK_product_dependencies_dependant_id FOREIGN KEY (dependant_id) REFERENCES products (id)",
				"ALTER TABLE product_dependencies ADD CONSTRAINT FK_product_dependencies_supporter_id FOREIGN KEY (supporter_id) REFERENCES products (id)",
		});


		dbUpdates.add(new String[]{
				"ALTER TABLE account_events DROP COLUMN delivered_count;"
		});

	}

	public BootstrapBean() {
	}

	private static void deleteMenu(String menupath) {
		dbUpdates.add(new String[]{
				"delete from menu_navigation where item_id in (select id from menuitem where url in ( '" + menupath + "'))",
				"delete from menuitem where url in ('" + menupath + "')",
		});
	}

	/**
	 * Runs a "ALTER TABLE
	 * <table>
	 * <statement>" for each of tables.
	 *
	 * @param alterStatement e.g. "ADD meta json"
	 * @param tables         table name strings
	 * @return1
	 */
	private static final String[] alterTables(String alterStatement, String... tables) {
		String[] strings = new String[tables.length];
		for (int i = 0; i < tables.length; i++) {
			strings[i] = "ALTER TABLE  \"" + tables[i] + "\" " + alterStatement;
		}
		return strings;
	}

	@PostConstruct
	public void bootstrap() {
		this.doDBUpdates();
	}

	private void doDBUpdates() {
		DBModel dBm = dbModelFacade.findLastRevision();
		Integer upIdx = dbUpdates.size() - 1;
		if (dBm != null) {
			Integer revId = dBm.getRevision();

			// Check if we have unapplied updates
			if ((dbUpdates.size() - 1) > revId) {
				// Oh yes we do

				this.executeUpdates(revId, upIdx);
			} else if (upIdx < revId) {
				throw new RuntimeException("Sanity check failed! DB is newer than the codebase!, should be: "+ revId);
			}
		} else {
			// DB is up to date by default! We need to mark the current version
			// down though.
			dBm = new DBModel();
			dBm.setRevision(upIdx);
			dbModelFacade.create(dBm);
		}
	}

	private void executeUpdates(Integer dbRev, Integer targetRev) {
		while (dbRev < targetRev) {
			dbRev++;

			System.out.format("attempt to upgrade db from version %d -> %d", (dbRev - 1), dbRev);

			String[] queries = dbUpdates.get(dbRev);
			for (String query : queries) {
				if (!query.isEmpty()) {
					dbModelFacade.updateModel(query);
				}
			}
			System.out.println("update ok!");

			DBModel dBm = new DBModel();
			dBm.setRevision(dbRev);
			dbModelFacade.create(dBm);
		}
	}
	// We will never run this again with empty database
	//	public void saneDefaults() {
	//		User adminUser = userFacade.findByLogin("admin");
	//		if (adminUser == null) {
	//			adminUser = new User();
	//			adminUser.setLogin("admin");
	//			// adminUser.setSuperadmin(true);
	//			adminUser.resetPassword("admin");
	//			userFacade.create(adminUser);
	//		}
	//	}

}