All Downloads are FREE. Search and download functionalities are using the official Maven repository.

base.query.SqlTables Maven / Gradle / Ivy

Go to download

A collection of basic java utility classes that provide basic features for a standalone/simple JEE application. Backed by a Cassandra, MySQL, or SQLite database, it provides, web page templates, user and group management, and a searchable online audit log of all user activity.

There is a newer version: 1.5.4
Show newest version
/*
 This is free and unencumbered software released into the public domain.

 Anyone is free to copy, modify, publish, use, compile, sell, or
 distribute this software, either in source code form or as a compiled
 binary, for any purpose, commercial or non-commercial, and by any
 means.

 In jurisdictions that recognize copyright laws, the author or authors
 of this software dedicate any and all copyright interest in the
 software to the public domain. We make this dedication for the benefit
 of the public at large and to the detriment of our heirs and
 successors. We intend this dedication to be an overt act of
 relinquishment in perpetuity of all present and future rights to this
 software under copyright law.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
package base.query;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import base.Query;
import base.QueryResult;
import base.security.PermissionException;

/**
 * Report on each of the current system settings.
 */
public class SqlTables extends Query {

	private DataSource ds;
	private String owner;

	/**
	 * Unused constructor for the ServiceLoader
	 */
	public SqlTables() {
	}

	/**
	 *
	 * @param ds
	 * @throws SQLException
	 */
	public SqlTables(DataSource ds, String owner) throws SQLException {
		this.ds = ds;
		this.owner = owner;
	}

	public List execute() throws IOException {
		List results = null;
		Connection c = null;

		try {
			c = ds.getConnection();
			c.setAutoCommit(false);

			results = executeQuery(c);

			c.rollback();
			c.close();
			c = null;
		} catch (SQLException e) {
			if(c != null) {
				try { c.rollback(); } catch (SQLException e1) { }
				try { c.close(); } catch (SQLException e1) { }
			}
			throw new IOException(e);
		}

		return results;
	}

	/**
	 * Return each setting in the form of key value pairs.
	 */
	public List executeQuery(Connection c) throws SQLException {
		List list = new ArrayList<>();

		PreparedStatement s = null;
		ResultSet r = null;
		Map tables = new Hashtable<>();

		// Build the list of tables, each with its associated columuns
		try {
			s = c.prepareStatement(
					"select distinct table_name,column_name,data_type,data_length,column_id " +
					"from all_tab_columns " +
					"where owner = ?" +
					"order by table_name,column_id");
			s.setString(1, owner);
			r = s.executeQuery();
			while(r.next()) {
				String tableName = r.getString(1);
				if(!tables.containsKey(tableName)) {
					TableInfo t = new TableInfo(tableName);
					tables.put(tableName, t);
					list.add(t);
				}
				tables.get(tableName).columns.add(new String[]{r.getString(2), r.getString(3), r.getString(4)});
			}
			r.close();
			r = null;
			s.close();
			s = null;
		} finally {
			if(r != null) { try { r.close(); } catch(Exception f) {} }
			if(s != null) { try { s.close(); } catch(Exception f) {} }
		}

		// Build the list of foreign key constraints associated with a table
		try {
			s = c.prepareStatement(
					"SELECT " +
							"c_list.CONSTRAINT_NAME as NAME, " +
							"c_src.TABLE_NAME as SRC_TABLE, " +
							"c_src.COLUMN_NAME as SRC_COLUMN, " +
							"c_dest.TABLE_NAME as DEST_TABLE, " +
							"c_dest.COLUMN_NAME as DEST_COLUMN " +
					"FROM ALL_CONSTRAINTS c_list, ALL_CONS_COLUMNS c_src, ALL_CONS_COLUMNS c_dest " +
					"WHERE c_list.CONSTRAINT_NAME = c_src.CONSTRAINT_NAME " +
							"AND c_list.R_CONSTRAINT_NAME = c_dest.CONSTRAINT_NAME " +
							"AND c_list.CONSTRAINT_TYPE = 'R' " +
							"and (c_src.owner=? or c_dest.owner=?) " +
					"GROUP BY c_list.CONSTRAINT_NAME, c_src.TABLE_NAME,  " +
							"c_src.COLUMN_NAME, c_dest.TABLE_NAME, c_dest.COLUMN_NAME "
					);
			s.setString(1, owner);
			s.setString(2, owner);
			r = s.executeQuery();
			while(r.next()) {
				String tableName = r.getString(2);
				String tableName2 = r.getString(4);
				if(!tables.containsKey(tableName)) {
					TableInfo t = new TableInfo(tableName);
					tables.put(tableName, t);
					list.add(t);
				}
				if(!tables.containsKey(tableName2)) {
					TableInfo t = new TableInfo(tableName2);
					tables.put(tableName2, t);
					list.add(t);
				}
				tables.get(tableName).addKey(r.getString(1), r.getString(2), r.getString(3), r.getString(4), r.getString(5));
				tables.get(tableName2).addKey(r.getString(1), r.getString(2), r.getString(3), r.getString(4), r.getString(5));
			}
			r.close();
			r = null;
			s.close();
			s = null;
		} finally {
			if(r != null) { try { r.close(); } catch(Exception f) {} }
			if(s != null) { try { s.close(); } catch(Exception f) {} }
		}

		// Build the list of unique constraints associated with a table
		try {
			s = c.prepareStatement(
					"select c.constraint_name, c.table_name, c.column_name, c.position " +
					"from all_constraints a " +
					"    join all_cons_columns c on (c.constraint_name = a.constraint_name and c.owner=a.owner) " +
					"where a.constraint_type = 'U' and a.owner=?"
			);
			s.setString(1, owner);
			r = s.executeQuery();
			while(r.next()) {
				String tableName = r.getString(2);
				if(!tables.containsKey(tableName)) {
					TableInfo t = new TableInfo(tableName);
					tables.put(tableName, t);
					list.add(t);
				}
				tables.get(tableName).addUniqueKey(r.getString(1), r.getString(3), r.getInt(4));
			}
			r.close();
			r = null;
			s.close();
			s = null;
		} finally {
			if(r != null) { try { r.close(); } catch(Exception f) {} }
			if(s != null) { try { s.close(); } catch(Exception f) {} }
		}

		return list;
	}

	@Override
	public String getJsonParameters() {
		return "{\"owner\":\"" + owner + "\"}";
	}

	@Override
	public Query newWithParameters(Map parameters) throws IOException, PermissionException {
		throw new IllegalArgumentException("SqlTables may not be instantiated with a parameter map.");
	}

}


class TableInfo implements QueryResult {

	public String tableName;
	public List columns = new LinkedList<>();
	public List foreignKeys = new LinkedList<>();
	public Map> constraints = new Hashtable<>();

	public TableInfo(String name) {
		this.tableName = name;
	}

	public void addKey(String key, String srcTable, String srcColumn, String dstTable, String dstColumn) {
		foreignKeys.add(new String[]{key, srcTable, srcColumn, dstTable, dstColumn});
	}

	public void addUniqueKey(String key, String column, int position) {
		Map u = constraints.get(key);

		if(u == null) {
			u = new Hashtable<>();
			constraints.put(key, u);
		}

		u.put(column, position);
	}

	public String toJson() {
		StringBuffer b = new StringBuffer();

		b.append("{\n    \"name\":\"");
		b.append(tableName);
		b.append("\",\n    \"cols\":[\n");
		boolean first = true;
		for(String[] column : columns) {
			if(first) {
				first = false;
			} else {
				b.append("\",\n");
			}
			b.append("        \"");
			b.append(column[0]);
			b.append(" ");
			b.append(column[1]);
			if(!column[1].equalsIgnoreCase("date") && !column[1].equalsIgnoreCase("timestamp")) {
				b.append("(");
				b.append(column[2]);
				b.append(")");
			}
		}
		if(!first) {
			b.append("\"\n");
		}

		b.append("        ],\n");
		b.append("    \"keys\":[");
		first = true;
		for(String key : constraints.keySet()) {
			if(first) {
				first = false;
				b.append("\n");
			} else {
				b.append("\",\n");
			}
			b.append("        \"");
			b.append(key);
			b.append("=");
			for(Map.Entry k : constraints.get(key).entrySet()) {
				b.append(k.getKey());
				b.append(" ");
			}
		}
		for(String[] key : foreignKeys) {
			if(first) {
				first = false;
				b.append("\n");
			} else {
				b.append("\",\n");
			}
			b.append("        \"");
			b.append(key[0]);
			b.append("=");
			b.append(key[1]);
			b.append(".");
			b.append(key[2]);
			b.append(" -> ");
			b.append(key[3]);
			b.append(".");
			b.append(key[4]);
		}
		if(!first) {
			b.append("\"\n        ]\n");
		} else {
			b.append("]\n");
		}


		b.append("}");

		return b.toString();
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy