Example usage for java.sql Connection setTransactionIsolation

List of usage examples for java.sql Connection setTransactionIsolation

Introduction

In this page you can find the example usage for java.sql Connection setTransactionIsolation.

Prototype

void setTransactionIsolation(int level) throws SQLException;

Source Link

Document

Attempts to change the transaction isolation level for this Connection object to the one given.

Usage

From source file:org.apache.hadoop.hive.metastore.MyXid.java

@Override
public boolean grantRoleToRole(String roleName, List<String> roles)
        throws NoSuchObjectException, InvalidObjectException, MetaException {
    Connection con = null;
    ;/*from  w  ww  .j a va  2 s  .c o  m*/
    Statement ps = null;
    boolean success = false;

    roleName = roleName.toLowerCase();
    List<String> roleLowerCase = new ArrayList<String>(roles.size());
    for (String role : roles) {
        roleLowerCase.add(role.toLowerCase());
    }

    try {
        con = getGlobalConnection();
    } catch (MetaStoreConnectException e1) {
        LOG.error("grant role error, role=" + roleName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("grant role error, role=" + roleName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setAutoCommit(false);
        con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        ps = con.createStatement();

        String sql = "select role_name from tdwrole where role_name='" + roleName.toLowerCase() + "'";

        boolean isRoleFind = false;
        ResultSet roleSet = ps.executeQuery(sql);
        while (roleSet.next()) {
            isRoleFind = true;
            break;
        }

        roleSet.close();

        if (!isRoleFind) {
            throw new NoSuchObjectException("can not find role:" + roleName);
        }

        Set<String> sonRoleNameSet = new HashSet<String>();
        sql = "select sonrole_name from tdwsonrole where role_name='" + roleName.toLowerCase() + "'";

        ResultSet sonroleSet = ps.executeQuery(sql);
        while (sonroleSet.next()) {
            sonRoleNameSet.add(sonroleSet.getString(1));
        }
        sonroleSet.close();

        List<String> needAddRoles = new ArrayList<String>();
        for (String role : roles) {
            if (!roleName.equalsIgnoreCase(role) && !sonRoleNameSet.contains(role)) {
                needAddRoles.add(role);
            }
        }

        if (!needAddRoles.isEmpty()) {
            for (String role : needAddRoles) {
                ps.addBatch("insert into tdwsonrole(role_name, sonrole_name) values('" + roleName.toLowerCase()
                        + "', '" + role.toLowerCase() + "')");
            }
            ps.executeBatch();
        }

        con.commit();
        success = true;
    } catch (SQLException sqlex) {
        sqlex.printStackTrace();
        LOG.error("grant role error, role=" + roleName + ", msg=" + sqlex.getMessage());
        throw new MetaException(sqlex.getMessage());
    } finally {
        if (!success) {
            try {
                con.rollback();
            } catch (SQLException e) {
            }
        }

        closeStatement(ps);
        closeConnection(con);
    }

    return success;
}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

@Override
public boolean revokeAuthOnDb(String who, List<String> privileges, String db)
        throws NoSuchObjectException, InvalidObjectException, MetaException {
    Connection con = null;
    ;/* w  w  w  .  j  a v  a 2  s . com*/
    PreparedStatement ps = null;
    boolean success = false;

    success = false;
    who = who.toLowerCase();
    db = db.toLowerCase();

    try {
        con = getGlobalConnection();
    } catch (MetaStoreConnectException e1) {
        LOG.error("revoke auth on db error, who=" + who + ", db=" + db + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("revoke auth on db error, who=" + who + ", db=" + db + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setAutoCommit(false);
        con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);

        ps = con.prepareStatement("select db_name from router where db_name=?");
        ps.setString(1, db.toLowerCase());
        boolean isDbfind = false;

        ResultSet dbSet = ps.executeQuery();

        while (dbSet.next()) {
            isDbfind = true;
            break;
        }

        dbSet.close();

        if (!isDbfind) {
            LOG.error("revoke auth on db error, who=" + who + ", db=" + db);
            throw new NoSuchObjectException("can not find db:" + db);
        }

        ps = con.prepareStatement("select alter_priv, create_priv, createview_priv, "
                + " delete_priv, drop_priv, index_priv, insert_priv, select_priv, showview_priv,"
                + " update_priv from dbpriv where user_name=? and db_name=?");

        ps.setString(1, who);
        ps.setString(2, db);
        boolean isPrivFind = false;

        boolean selPriv = false;
        boolean insertPriv = false;
        boolean createPriv = false;
        boolean dropPriv = false;
        boolean deletePriv = false;
        boolean alterPriv = false;
        boolean updatePriv = false;
        boolean indexPriv = false;
        boolean showViewPriv = false;
        boolean createViewPriv = false;

        ResultSet privSet = ps.executeQuery();

        while (privSet.next()) {
            isPrivFind = true;
            alterPriv = privSet.getBoolean(1);
            createPriv = privSet.getBoolean(2);
            createViewPriv = privSet.getBoolean(3);
            deletePriv = privSet.getBoolean(4);
            dropPriv = privSet.getBoolean(5);
            indexPriv = privSet.getBoolean(6);
            insertPriv = privSet.getBoolean(7);
            selPriv = privSet.getBoolean(8);
            showViewPriv = privSet.getBoolean(9);
            updatePriv = privSet.getBoolean(10);

            break;
        }

        privSet.close();
        ps.close();

        if (!isPrivFind) {
            LOG.error("revoke auth on db error, who=" + who + ", db=" + db);
            throw new NoSuchObjectException("User " + who + " does not have privileges on db: " + db);
        }

        if (privileges == null) {
            LOG.error("revoke auth on db error, who=" + who + ", db=" + db);
            throw new InvalidObjectException("No privileges are given!");
        }

        for (String priv : privileges) {
            if (priv.equals("TOK_SELECT_PRI")) {
                selPriv = false;
            } else if (priv.equals("TOK_INSERT_PRI")) {
                insertPriv = false;
            } else if (priv.equals("TOK_CREATE_PRI")) {
                createPriv = false;
            } else if (priv.equals("TOK_DROP_PRI")) {
                dropPriv = false;
            } else if (priv.equals("TOK_DELETE_PRI")) {
                deletePriv = false;
            } else if (priv.equals("TOK_ALTER_PRI")) {
                alterPriv = false;
            } else if (priv.equals("TOK_UPDATE_PRI")) {
                updatePriv = false;
            } else if (priv.equals("TOK_INDEX_PRI")) {
                indexPriv = false;
            } else if (priv.equals("TOK_CREATEVIEW_PRI")) {
                createViewPriv = false;
            } else if (priv.equals("TOK_SHOWVIEW_PRI")) {
                showViewPriv = false;
            } else if (priv.equals("TOK_ALL_PRI")) {
                selPriv = false;
                insertPriv = false;
                createPriv = false;
                dropPriv = false;
                deletePriv = false;
                alterPriv = false;
                updatePriv = false;
                indexPriv = false;
                createViewPriv = false;
                showViewPriv = false;
            } else {
                LOG.error("revoke auth on db error, who=" + who + ", db=" + db);
                throw new InvalidObjectException("Privilege does not exist: " + priv);
            }

        }

        ps = con.prepareStatement("update dbpriv set alter_priv=?, create_priv=?, createview_priv=?, "
                + " delete_priv=?, drop_priv=?, index_priv=?, insert_priv=?, select_priv=?, showview_priv=?,"
                + " update_priv=? where user_name=? and db_name=? ");

        ps.setBoolean(1, alterPriv);
        ps.setBoolean(2, createPriv);
        ps.setBoolean(3, createViewPriv);
        ps.setBoolean(4, deletePriv);
        ps.setBoolean(5, dropPriv);
        ps.setBoolean(6, indexPriv);
        ps.setBoolean(7, insertPriv);
        ps.setBoolean(8, selPriv);
        ps.setBoolean(9, showViewPriv);
        ps.setBoolean(10, updatePriv);

        ps.setString(11, who);
        ps.setString(12, db);

        ps.executeUpdate();

        con.commit();
        success = true;
    } catch (SQLException ex) {
        LOG.error("revoke auth on db error, who=" + who + ", db=" + db);
        ex.printStackTrace();
        throw new MetaException(ex.getMessage());
    } finally {
        if (!success) {
            try {
                con.rollback();
            } catch (SQLException e) {
            }
        }

        closeStatement(ps);
        closeConnection(con);
    }

    return success;
}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

@Override
public void addSerdeProps(String dbName, String tblName, String modifyUser, Map<String, String> props)
        throws InvalidOperationException, MetaException {
    Connection con;
    PreparedStatement ps = null;//from   w w  w .ja v a2s.  com
    Statement stmt = null;
    boolean success = false;

    dbName = dbName.toLowerCase();
    tblName = tblName.toLowerCase();

    try {
        con = getSegmentConnection(dbName);
    } catch (MetaStoreConnectException e1) {
        LOG.error("add serde props error, db=" + dbName + ", tbl=" + tblName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("add serde props error, db=" + dbName + ", tbl=" + tblName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setAutoCommit(false);
        con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        stmt = con.createStatement();

        String sql = "select tbls.tbl_id from tbls where " + "tbls.db_name='" + dbName + "' and tbls.tbl_name='"
                + tblName + "'";

        boolean isTblFind = false;
        long tblID = 0;

        ResultSet tblSet = stmt.executeQuery(sql);
        while (tblSet.next()) {
            isTblFind = true;
            tblID = tblSet.getLong(1);
        }

        tblSet.close();

        if (!isTblFind) {
            throw new MetaException("can not find table " + dbName + ":" + tblName);
        }

        Map<String, String> tblParamMap = new HashMap<String, String>();
        Map<String, String> serdeParamMap = new HashMap<String, String>();
        sql = "select param_type, param_key, param_value from table_params where tbl_id=" + tblID
                + " and (param_type='SERDE' or param_type='TBL')";
        ResultSet paramSet = stmt.executeQuery(sql);
        String type = null;
        while (paramSet.next()) {
            type = paramSet.getString(1);
            if (type.equalsIgnoreCase("TBL")) {
                tblParamMap.put(paramSet.getString(2), paramSet.getString(3));
            } else {
                serdeParamMap.put(paramSet.getString(2), paramSet.getString(3));
            }
        }
        paramSet.close();

        boolean containTime = false;
        boolean contailUser = false;
        if (tblParamMap.containsKey("last_modified_time"))
            containTime = true;
        if (tblParamMap.containsKey("last_modified_by"))
            contailUser = true;

        Map<String, String> needUpdateMap = new HashMap<String, String>();
        Map<String, String> needAddMap = new HashMap<String, String>();

        for (Entry<String, String> entry : props.entrySet()) {
            if (serdeParamMap.containsKey(entry.getKey())) {
                needUpdateMap.put(entry.getKey(), entry.getValue());
            } else {
                needAddMap.put(entry.getKey(), entry.getValue());
            }
        }

        if (!needUpdateMap.isEmpty() || containTime || contailUser) {
            ps = con.prepareStatement("update table_params set param_value=? where "
                    + " tbl_id=? and param_type=? and param_key=?");
            for (Entry<String, String> entry : needUpdateMap.entrySet()) {
                ps.setString(1, entry.getValue());
                ps.setLong(2, tblID);
                ps.setString(3, "SERDE");
                ps.setString(4, entry.getKey());
                ps.addBatch();
            }

            if (containTime) {
                ps.setString(1, String.valueOf(System.currentTimeMillis() / 1000));
                ps.setLong(2, tblID);
                ps.setString(3, "TBL");
                ps.setString(4, "last_modified_time");
                ps.addBatch();
            }

            if (contailUser) {
                ps.setString(1, modifyUser);
                ps.setLong(2, tblID);
                ps.setString(3, "TBL");
                ps.setString(4, "last_modified_by");
                ps.addBatch();
            }

            ps.executeBatch();
            ps.close();
        }

        if (!needAddMap.isEmpty() || !containTime || !contailUser) {
            ps = con.prepareStatement("insert into table_params(tbl_id, param_type, "
                    + "param_key, param_value) values(?,?,?,?)");

            for (Map.Entry<String, String> entry : needAddMap.entrySet()) {
                ps.setLong(1, tblID);
                ps.setString(2, "SERDE");
                ps.setString(3, entry.getKey());
                ps.setString(4, entry.getValue());
                ps.addBatch();
            }

            if (!containTime) {
                ps.setLong(1, tblID);
                ps.setString(2, "TBL");
                ps.setString(3, "last_modified_time");
                ps.setString(4, String.valueOf(System.currentTimeMillis() / 1000));
                ps.addBatch();
            }

            if (!contailUser) {
                ps.setLong(1, tblID);
                ps.setString(2, "TBL");
                ps.setString(3, "last_modified_by");
                ps.setString(4, modifyUser);
                ps.addBatch();
            }

            ps.executeBatch();
            ps.close();
        }

        con.commit();
        success = true;
    } catch (SQLException ex) {
        ex.printStackTrace();
        LOG.error("add serde props error, db=" + dbName + ", tbl=" + tblName + ", msg=" + ex.getMessage());
        throw new MetaException(ex.getMessage());
    } finally {
        if (!success) {
            try {
                con.rollback();
            } catch (SQLException e) {
            }
        }

        closeStatement(ps);
        closeStatement(stmt);
        closeConnection(con);
    }

    return;
}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

@Override
public boolean addUserGroup(group newGroup, String user) throws MetaException {
    Connection con = null;
    ;/*from  w  w  w  . jav a2 s . co  m*/
    PreparedStatement ps = null;
    boolean success = false;
    newGroup.setGroupName(newGroup.getGroupName().toLowerCase());
    user = user.toLowerCase();

    try {
        con = getGlobalConnection();
    } catch (MetaStoreConnectException e1) {
        LOG.error("add user group error, creator=" + newGroup.getCreator() + ", group="
                + newGroup.getGroupName() + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("add user group error, creator=" + newGroup.getCreator() + ", group="
                + newGroup.getGroupName() + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setAutoCommit(false);
        con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);

        ps = con.prepareStatement("insert into usergroup(creator, group_name)" + " values(?,?)");
        ps.setString(1, newGroup.getCreator().toLowerCase());
        ps.setString(2, newGroup.getGroupName());
        ps.executeUpdate();
        ps.close();

        String addList = newGroup.getUserList();
        if (addList != null && !addList.isEmpty()) {
            ps = con.prepareStatement("update tdwuser set group_name=? where user_name=?");

            String[] addArray = addList.split(",");
            for (int i = 0; i < addArray.length; i++) {
                ps.setString(1, newGroup.getGroupName());
                ps.setString(2, addArray[i].toLowerCase());
                ps.addBatch();
            }

            ps.executeBatch();
        }

        con.commit();
        success = true;
    } catch (SQLException sqlex) {
        LOG.error("add user group error, creator=" + newGroup.getCreator() + ", group="
                + newGroup.getGroupName() + ", msg=" + sqlex.getMessage());
        sqlex.printStackTrace();
        throw new MetaException(sqlex.getMessage());
    } finally {
        if (!success) {
            try {
                con.rollback();
            } catch (SQLException e) {
            }
        }

        closeStatement(ps);
        closeConnection(con);
    }

    return success;
}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

@Override
public List<FieldSchema> getPartFieldsJdbc(String dbName, String tableName) throws MetaException {
    Connection con = null;
    ;//from  w ww.  j  ava 2  s .c  om
    Statement ps = null;
    boolean success = false;
    List<FieldSchema> columnInfo = new ArrayList<FieldSchema>();

    dbName = dbName.toLowerCase();
    tableName = tableName.toLowerCase();

    try {
        con = getSegmentConnection(dbName);
    } catch (MetaStoreConnectException e1) {
        LOG.error(
                "get partition field error, db=" + dbName + ", tbl=" + tableName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error(
                "get partition field error, db=" + dbName + ", tbl=" + tableName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setAutoCommit(false);
        con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        ps = con.createStatement();

        String sql = "select tbl_id, pri_part_key, sub_part_key from tbls where db_name='" + dbName + "' "
                + " and tbl_name='" + tableName + "'";

        ResultSet tblSet = ps.executeQuery(sql);
        String priPartKey = null;
        String subPartKey = null;
        long tblID = 0;
        boolean isTblFind = false;

        while (tblSet.next()) {
            isTblFind = true;
            tblID = tblSet.getLong(1);
            priPartKey = tblSet.getString(2);
            subPartKey = tblSet.getString(3);
        }

        tblSet.close();

        if (isTblFind) {
            sql = "select column_name, type_name, comment, column_len from " + " columns where tbl_id=" + tblID
                    + " and ( column_name='" + priPartKey + "' or column_name='" + subPartKey + "')";

            ResultSet colSet = ps.executeQuery(sql);

            while (colSet.next()) {
                FieldSchema field = new FieldSchema();
                field.setName(colSet.getString(1));
                field.setType(colSet.getString(2));
                field.setComment(colSet.getString(3));

                columnInfo.add(field);
            }
        }

        con.commit();
        success = true;
    } catch (SQLException sqlex) {
        LOG.error("get partition field error, db=" + dbName + ", tbl=" + tableName + ", msg="
                + sqlex.getMessage());
        sqlex.printStackTrace();
        throw new MetaException(sqlex.getMessage());
    } finally {
        if (!success) {
            try {
                con.rollback();
            } catch (SQLException e) {
            }
        }

        closeStatement(ps);
        closeConnection(con);
    }

    return columnInfo;
}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

public boolean createDatabaseNoDistributeTransaction(Database db) throws MetaException {
    boolean success = false;
    Connection con;
    PreparedStatement ps = null;/*  w ww.j  a va 2 s  . c o  m*/
    db.setName(db.getName().toLowerCase());

    if (db.getMetastore() == null) {
        String slaveURL = getSegmentUrlByDbNameHashCode(db.getName());
        db.setMetastore(slaveURL);
    }
    int hashcode = getHashForDb(db.getName());

    try {
        con = getConnectionFromPool(db.getMetastore());
    } catch (MetaStoreConnectException e1) {
        LOG.error("create database error, db=" + db.getName() + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("create database error, db=" + db.getName() + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setAutoCommit(false);
        con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);

        ps = con.prepareStatement("INSERT INTO DBS(name, hdfs_schema, description, owner) VALUES(?,?,?,?)");
        ps.setString(1, db.getName());
        ps.setString(2, db.getHdfsscheme());
        ps.setString(3, db.getDescription());
        ps.setString(4, db.getOwner());
        ps.executeUpdate();

        Warehouse wh = new Warehouse(hiveConf);
        Path databasePath = wh.getDefaultDatabasePath(db.getName(), db.getHdfsscheme());
        wh.mkdirs(databasePath);

        con.commit();
        success = true;

    } catch (Exception x) {
        LOG.error("create database error, db=" + db.getName() + ", msg=" + x.getMessage());
        x.printStackTrace();
        try {
            con.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        throw new MetaException(x.getMessage());
    } finally {
        closeStatement(ps);
        closeConnection(con);
    }

    try {
        con = getGlobalConnection();
    } catch (MetaStoreConnectException e1) {
        LOG.error("create database error, db=" + db.getName() + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("create database error, db=" + db.getName() + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setAutoCommit(false);
        con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);

        ps = con.prepareStatement("INSERT INTO router(db_name, seg_addr, hashcode, owner) VALUES(?,?,?,?)");
        ps.setString(1, db.getName());
        ps.setString(2, db.getMetastore());
        ps.setInt(3, hashcode);
        ps.setString(4, db.getOwner());
        ps.executeUpdate();

        con.commit();
    } catch (Exception x) {
        LOG.error("create database error, db=" + db.getName() + ", msg=" + x.getMessage());
        x.printStackTrace();
        try {
            con.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        throw new MetaException(x.getMessage());
    } finally {
        closeStatement(ps);
        closeConnection(con);
    }

    return success;
}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

@Override
public void modifyColumnComment(String dbName, String tblName, String colName, String comment)
        throws InvalidOperationException, MetaException {
    Connection con = null;
    PreparedStatement ps = null;/*from  w w  w .  j av  a 2s . c o  m*/
    boolean success = false;

    dbName = dbName.toLowerCase();
    tblName = tblName.toLowerCase();

    try {
        con = getSegmentConnection(dbName);
    } catch (MetaStoreConnectException e1) {
        LOG.error("alter column comment error, db=" + dbName + ", tbl=" + tblName + ", column=" + colName
                + ", comment=" + comment + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("alter column comment error, db=" + dbName + ", tbl=" + tblName + ", column=" + colName
                + ", comment=" + comment + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setAutoCommit(false);
        con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);

        ps = con.prepareStatement("select tbls.tbl_id from tbls, columns where tbls.tbl_id=columns.tbl_id "
                + " and tbls.db_name=? and tbls.tbl_name=? and columns.column_name=?");
        long tblID = 0;
        boolean isColFind = false;
        ps.setString(1, dbName);
        ps.setString(2, tblName);
        ps.setString(3, colName.toLowerCase());

        ResultSet tSet = ps.executeQuery();
        while (tSet.next()) {
            tblID = tSet.getLong(1);
            isColFind = true;
            break;
        }

        tSet.close();
        ps.close();

        if (!isColFind) {
            LOG.error("alter table comment error, db=" + dbName + ", tbl=" + tblName + ", comment=" + comment);
            throw new MetaException("can not find table/column " + dbName + ":" + tblName + "/" + colName);
        }

        ps = con.prepareStatement("update columns set comment=? where tbl_id=? and column_name=?");
        ps.setString(1, comment);
        ps.setLong(2, tblID);
        ps.setString(3, colName.toLowerCase());
        ps.executeUpdate();

        con.commit();
        success = true;
    } catch (SQLException sqlex) {
        LOG.error("alter column comment error, db=" + dbName + ", tbl=" + tblName + ", column=" + colName
                + ", comment=" + comment + ", msg=" + sqlex.getMessage());
        sqlex.printStackTrace();
        throw new MetaException(sqlex.getMessage());
    } finally {
        if (!success) {
            try {
                con.rollback();
            } catch (SQLException e) {
            }
        }

        closeStatement(ps);
        closeConnection(con);
    }
}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

@Override
public void replaceCols(String dbName, String tblName, String modifyUser, List<FieldSchema> newCols)
        throws InvalidOperationException, MetaException {
    Connection con = null;
    PreparedStatement ps = null;/*from   w w  w.  j a v a  2s.  c  om*/
    boolean success = false;
    dbName = dbName.toLowerCase();
    tblName = tblName.toLowerCase();

    try {
        con = getSegmentConnection(dbName);
    } catch (MetaStoreConnectException e1) {
        LOG.error("replace column error, db=" + dbName + ", tbl=" + tblName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("replace column error, db=" + dbName + ", tbl=" + tblName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setAutoCommit(false);
        con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);

        ps = con.prepareStatement("select tbl_id, tbl_type, tbl_format, pri_part_type, serde_lib"
                + " from tbls where db_name=? and tbl_name=?");

        ps.setString(1, dbName);
        ps.setString(2, tblName);

        String tblType = null;
        String serdeLib = null;
        String tblFormat = null;
        String priPartType = null;
        boolean isPriPart = false;
        boolean isTblFind = false;
        long tblID = 0;

        ResultSet tblSet = ps.executeQuery();
        while (tblSet.next()) {
            isTblFind = true;
            tblID = tblSet.getLong(1);
            tblType = tblSet.getString(2);
            tblFormat = tblSet.getString(3);
            priPartType = tblSet.getString(4);
            serdeLib = tblSet.getString(5);

            isPriPart = priPartType != null;
        }

        tblSet.close();
        ps.close();

        if (!isTblFind) {
            throw new MetaException("can not find table " + dbName + ":" + tblName);
        }

        if (tblType.equalsIgnoreCase("VITURAL_VIEW")) {
            throw new MetaException("view can not replace column ");
        }

        if (!HiveConf.getBoolVar(hiveConf, ConfVars.ALTERSCHEMAACTIVATEREPLACE)) {
            throw new MetaException("replace columns is not supported rightnow");
        }

        if (tblType.equalsIgnoreCase("EXTERNAL_TABLE")
                && !HiveConf.getBoolVar(hiveConf, ConfVars.ALTERSCHEMAACTIVATEEXTTABLE)) {
            throw new MetaException("can not replace columns for a extenal table ");
        }

        if (!tblType.equalsIgnoreCase("EXTERNAL_TABLE")
                && (tblFormat != null && tblFormat.equalsIgnoreCase("text"))
                && (!HiveConf.getBoolVar(hiveConf, ConfVars.ALTERSCHEMAACTIVATETXTTABLE))) {
            throw new MetaException("can not replace columns for a text format table ");
        }

        if (!serdeLib.equals(MetadataTypedColumnsetSerDe.class.getName())
                && !serdeLib.equals(LazySimpleSerDe.class.getName())
                && !serdeLib.equals(ColumnarSerDe.class.getName())
                && !serdeLib.equals(DynamicSerDe.class.getName())
                && !serdeLib.equals(ProtobufSerDe.class.getName())) {
            throw new MetaException(
                    "Replace columns is not supported for this table. SerDe may be incompatible.");
        }

        if (serdeLib.equals("org.apache.hadoop.hive.serde.thrift.columnsetSerDe")) {
            ps = con.prepareStatement("update tbls set serde_lib=? where tbl_id=?");
            ps.setString(1, LazySimpleSerDe.class.getName());
            ps.setLong(2, tblID);
            ps.executeUpdate();
        }

        Map<String, String> tblParamMap = new HashMap<String, String>();
        ps = con.prepareStatement(
                "select param_key, param_value from table_params where tbl_id=? and param_type='TBL'");
        ps.setLong(1, tblID);
        ResultSet paramSet = ps.executeQuery();
        while (paramSet.next()) {
            tblParamMap.put(paramSet.getString(1), paramSet.getString(2));
        }
        paramSet.close();
        ps.close();
        boolean containTime = false;
        boolean contailUser = false;
        if (tblParamMap.containsKey("last_modified_time"))
            containTime = true;
        if (tblParamMap.containsKey("last_modified_by"))
            contailUser = true;

        if (containTime && contailUser) {
            ps = con.prepareStatement(
                    "update table_params set param_value=? where tbl_id=? and param_type='TBL' and param_key=?");
            ps.setString(1, String.valueOf(System.currentTimeMillis() / 1000));
            ps.setLong(2, tblID);
            ps.setString(3, "last_modified_time");
            ps.addBatch();
            ps.setString(1, modifyUser);
            ps.setLong(2, tblID);
            ps.setString(3, "last_modified_by");
            ps.addBatch();

            ps.executeBatch();
            ps.close();
        } else if (!containTime && !contailUser) {
            ps = con.prepareStatement("insert into table_params(tbl_id, param_type, param_key, param_value) "
                    + " values(?,?,?,?)");
            ps.setLong(1, tblID);
            ps.setString(2, "TBL");
            ps.setString(3, "last_modified_time");
            ps.setString(4, String.valueOf(System.currentTimeMillis() / 1000));
            ps.addBatch();

            ps.setLong(1, tblID);
            ps.setString(2, "TBL");
            ps.setString(3, "last_modified_by");
            ps.setString(4, modifyUser);

            ps.addBatch();

            ps.executeBatch();
            ps.close();
        } else if (containTime && !contailUser) {
            ps = con.prepareStatement(
                    "update table_params set param_value=? where tbl_id=? and param_type='TBL' and param_key=?");
            ps.setString(1, String.valueOf(System.currentTimeMillis() / 1000));
            ps.setLong(2, tblID);
            ps.setString(3, "last_modified_time");
            ps.addBatch();

            ps.executeBatch();
            ps.close();

            ps = con.prepareStatement("insert into table_params(tbl_id, param_type, param_key, param_value) "
                    + " values(?,?,?,?)");

            ps.setLong(1, tblID);
            ps.setString(2, "TBL");
            ps.setString(3, "last_modified_by");
            ps.setString(4, modifyUser);

            ps.addBatch();

            ps.executeBatch();
            ps.close();
        } else {
            ps = con.prepareStatement(
                    "update table_params set param_value=? where tbl_id=? and param_type='TBL' and param_key=?");

            ps.setString(1, modifyUser);
            ps.setLong(2, tblID);
            ps.setString(3, "last_modified_by");
            ps.addBatch();

            ps.executeBatch();
            ps.close();

            ps = con.prepareStatement("insert into table_params(tbl_id, param_type, param_key, param_value) "
                    + " values(?,?,?,?)");
            ps.setLong(1, tblID);
            ps.setString(2, "TBL");
            ps.setString(3, "last_modified_time");
            ps.setString(4, String.valueOf(System.currentTimeMillis() / 1000));
            ps.addBatch();

            ps.executeBatch();
            ps.close();
        }

        ps = con.prepareStatement("delete from columns where tbl_id=?");
        ps.setLong(1, tblID);
        ps.executeUpdate();
        ps.close();

        ps = con.prepareStatement("insert into columns(column_index, tbl_id, column_name "
                + ",type_name, comment) values(?,?,?,?,?)");
        long index = 0;

        for (FieldSchema field : newCols) {
            ps.setLong(1, index);
            ps.setLong(2, tblID);
            ps.setString(3, field.getName().toLowerCase());
            ps.setString(4, field.getType());
            ps.setString(5, field.getComment());

            ps.addBatch();
            index++;
        }

        ps.executeBatch();
        ps.close();

        con.commit();
        success = true;
    } catch (SQLException ex) {
        ex.printStackTrace();
        LOG.error("replace column error, db=" + dbName + ", tbl=" + tblName + ", msg=" + ex.getMessage());
        throw new MetaException(ex.getMessage());
    } finally {
        if (!success) {
            try {
                con.rollback();
            } catch (SQLException e) {
            }
        }

        closeStatement(ps);
        closeConnection(con);
    }
    return;
}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

@Override
public boolean revokeRoleFromUser(String userName, List<String> roles)
        throws NoSuchObjectException, InvalidObjectException, MetaException {
    Connection con = null;
    ;/*  w  w  w.  j a v  a  2  s . co  m*/
    Statement ps = null;
    boolean success = false;

    userName = userName.toLowerCase();
    List<String> roleLowerCase = new ArrayList<String>(roles.size());
    for (String role : roles) {
        roleLowerCase.add(role.toLowerCase());
    }

    roles = roleLowerCase;

    try {
        con = getGlobalConnection();
    } catch (MetaStoreConnectException e1) {
        LOG.error("revoke role to user error , user=" + userName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("revoke role to user error , user=" + userName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setAutoCommit(false);
        con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        ps = con.createStatement();

        String sql = "select user_name from tdwuser where user_name='" + userName + "'";

        boolean isPrivFind = false;
        ResultSet userSet = ps.executeQuery(sql);

        while (userSet.next()) {
            isPrivFind = true;
            break;
        }

        userSet.close();

        if (!isPrivFind) {
            throw new NoSuchObjectException("can not find user:" + userName);
        }

        for (String role : roles) {
            sql = "select role_name from tdwrole where role_name='" + role + "'";
            boolean isRoleFind = false;
            ResultSet roleTempSet = ps.executeQuery(sql);

            while (roleTempSet.next()) {
                isRoleFind = true;
            }

            roleTempSet.close();

            if (!isRoleFind) {
                throw new InvalidObjectException("Role does not exist: " + role);
            }
        }

        for (String role : roles) {
            ps.addBatch(
                    "delete from tdwuserrole where user_name='" + userName + "' and role_name='" + role + "'");
        }

        ps.executeBatch();
        ps.clearBatch();

        con.commit();
        success = true;
    } catch (SQLException ex) {
        LOG.error("revoke role from user error , user=" + userName + ", msg=" + ex.getMessage());
        throw new MetaException(ex.getMessage());
    } finally {
        if (!success) {
            try {
                con.rollback();
            } catch (SQLException e) {
            }
        }

        closeStatement(ps);
        closeConnection(con);
    }

    return success;
}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

@Override
public boolean grantRoleToUser(String userName, List<String> roles)
        throws NoSuchObjectException, InvalidObjectException, MetaException {
    Connection con = null;
    ;/*from   w w  w .ja v  a 2 s  . com*/
    PreparedStatement ps = null;
    boolean success = false;

    userName = userName.toLowerCase();
    List<String> roleLowerCase = new ArrayList<String>(roles.size());
    for (String role : roles) {
        roleLowerCase.add(role.toLowerCase());
    }

    roles = roleLowerCase;

    try {
        con = getGlobalConnection();
    } catch (MetaStoreConnectException e1) {
        LOG.error("grant role to user error , user=" + userName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("grant role to user error , user=" + userName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setAutoCommit(false);
        con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);

        ps = con.prepareStatement("select user_name from tdwuser where user_name=?");
        ps.setString(1, userName);

        boolean isPrivFind = false;
        ResultSet userSet = ps.executeQuery();

        while (userSet.next()) {
            isPrivFind = true;
            break;
        }

        userSet.close();
        ps.close();

        if (!isPrivFind) {
            throw new NoSuchObjectException("can not find user:" + userName);
        }

        ps = con.prepareStatement("select role_name from tdwuserrole where user_name=?");
        ps.setString(1, userName);

        List<String> roleSet = new ArrayList<String>();
        ResultSet roleRetSet = ps.executeQuery();
        while (roleRetSet.next()) {
            roleSet.add(roleRetSet.getString(1));
        }
        roleRetSet.close();
        ps.close();

        roles.removeAll(roleSet);

        if (!roles.isEmpty()) {
            ps = con.prepareStatement("insert into tdwuserrole(user_name, role_name) values(?,?)");

            for (String role : roles) {
                ps.setString(1, userName);
                ps.setString(2, role);
                ps.addBatch();
            }

            ps.executeBatch();
        }

        con.commit();
        success = true;
    } catch (SQLException ex) {
        LOG.error("grant auth sys error , user=" + userName + ", msg=" + ex.getMessage());
        ex.printStackTrace();
        throw new MetaException(ex.getMessage());
    } finally {
        if (!success) {
            try {
                con.rollback();
            } catch (SQLException e) {
            }
        }

        closeStatement(ps);
        closeConnection(con);
    }

    return success;
}