PageRenderTime 57ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/tags/release-0.0.0-rc0/hive/external/metastore/src/java/org/apache/hadoop/hive/metastore/ObjectStore.java

#
Java | 3285 lines | 2940 code | 234 blank | 111 comment | 505 complexity | c77e7956bd825332aaaf457243b8e157 MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause, JSON, CPL-1.0

Large files files are truncated, but you can click here to view the full file

  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. package org.apache.hadoop.hive.metastore;
  19. import java.util.ArrayList;
  20. import java.util.Collection;
  21. import java.util.Collections;
  22. import java.util.HashMap;
  23. import java.util.HashSet;
  24. import java.util.Iterator;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Set;
  28. import java.util.Map.Entry;
  29. import java.util.Properties;
  30. import java.util.concurrent.locks.Lock;
  31. import java.util.concurrent.locks.ReentrantLock;
  32. import javax.jdo.JDOHelper;
  33. import javax.jdo.JDOObjectNotFoundException;
  34. import javax.jdo.PersistenceManager;
  35. import javax.jdo.PersistenceManagerFactory;
  36. import javax.jdo.Query;
  37. import javax.jdo.Transaction;
  38. import javax.jdo.datastore.DataStoreCache;
  39. import org.antlr.runtime.CharStream;
  40. import org.antlr.runtime.CommonTokenStream;
  41. import org.antlr.runtime.RecognitionException;
  42. import org.apache.commons.logging.Log;
  43. import org.apache.commons.logging.LogFactory;
  44. import org.apache.hadoop.conf.Configurable;
  45. import org.apache.hadoop.conf.Configuration;
  46. import org.apache.hadoop.hive.common.FileUtils;
  47. import org.apache.hadoop.hive.conf.HiveConf;
  48. import org.apache.hadoop.hive.metastore.api.Database;
  49. import org.apache.hadoop.hive.metastore.api.FieldSchema;
  50. import org.apache.hadoop.hive.metastore.api.HiveObjectPrivilege;
  51. import org.apache.hadoop.hive.metastore.api.HiveObjectRef;
  52. import org.apache.hadoop.hive.metastore.api.HiveObjectType;
  53. import org.apache.hadoop.hive.metastore.api.Index;
  54. import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
  55. import org.apache.hadoop.hive.metastore.api.MetaException;
  56. import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
  57. import org.apache.hadoop.hive.metastore.api.Order;
  58. import org.apache.hadoop.hive.metastore.api.Partition;
  59. import org.apache.hadoop.hive.metastore.api.PrincipalPrivilegeSet;
  60. import org.apache.hadoop.hive.metastore.api.PrincipalType;
  61. import org.apache.hadoop.hive.metastore.api.PrivilegeBag;
  62. import org.apache.hadoop.hive.metastore.api.PrivilegeGrantInfo;
  63. import org.apache.hadoop.hive.metastore.api.Role;
  64. import org.apache.hadoop.hive.metastore.api.SerDeInfo;
  65. import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
  66. import org.apache.hadoop.hive.metastore.api.Table;
  67. import org.apache.hadoop.hive.metastore.api.Type;
  68. import org.apache.hadoop.hive.metastore.model.MDatabase;
  69. import org.apache.hadoop.hive.metastore.model.MFieldSchema;
  70. import org.apache.hadoop.hive.metastore.model.MIndex;
  71. import org.apache.hadoop.hive.metastore.model.MOrder;
  72. import org.apache.hadoop.hive.metastore.model.MPartition;
  73. import org.apache.hadoop.hive.metastore.model.MDBPrivilege;
  74. import org.apache.hadoop.hive.metastore.model.MPartitionColumnPrivilege;
  75. import org.apache.hadoop.hive.metastore.model.MPartitionPrivilege;
  76. import org.apache.hadoop.hive.metastore.model.MRole;
  77. import org.apache.hadoop.hive.metastore.model.MTableColumnPrivilege;
  78. import org.apache.hadoop.hive.metastore.model.MGlobalPrivilege;
  79. import org.apache.hadoop.hive.metastore.model.MRoleMap;
  80. import org.apache.hadoop.hive.metastore.model.MSerDeInfo;
  81. import org.apache.hadoop.hive.metastore.model.MStorageDescriptor;
  82. import org.apache.hadoop.hive.metastore.model.MTable;
  83. import org.apache.hadoop.hive.metastore.model.MTablePrivilege;
  84. import org.apache.hadoop.hive.metastore.model.MType;
  85. import org.apache.hadoop.hive.metastore.parser.FilterLexer;
  86. import org.apache.hadoop.hive.metastore.parser.FilterParser;
  87. import org.apache.hadoop.hive.metastore.parser.ExpressionTree.ANTLRNoCaseStringStream;
  88. import org.apache.hadoop.util.StringUtils;
  89. /**
  90. * This class is the interface between the application logic and the database
  91. * store that contains the objects. Refrain putting any logic in mode.M* objects
  92. * or in this file as former could be auto generated and this class would need
  93. * to be made into a interface that can read both from a database and a
  94. * filestore.
  95. */
  96. public class ObjectStore implements RawStore, Configurable {
  97. private static Properties prop = null;
  98. private static PersistenceManagerFactory pmf = null;
  99. private static Lock pmfPropLock = new ReentrantLock();
  100. private static final Log LOG = LogFactory.getLog(ObjectStore.class.getName());
  101. private static enum TXN_STATUS {
  102. NO_STATE, OPEN, COMMITED, ROLLBACK
  103. }
  104. private static final Map<String, Class> PINCLASSMAP;
  105. static {
  106. Map<String, Class> map = new HashMap();
  107. map.put("table", MTable.class);
  108. map.put("storagedescriptor", MStorageDescriptor.class);
  109. map.put("serdeinfo", MSerDeInfo.class);
  110. map.put("partition", MPartition.class);
  111. map.put("database", MDatabase.class);
  112. map.put("type", MType.class);
  113. map.put("fieldschema", MFieldSchema.class);
  114. map.put("order", MOrder.class);
  115. PINCLASSMAP = Collections.unmodifiableMap(map);
  116. }
  117. private boolean isInitialized = false;
  118. private PersistenceManager pm = null;
  119. private Configuration hiveConf;
  120. int openTrasactionCalls = 0;
  121. private Transaction currentTransaction = null;
  122. private TXN_STATUS transactionStatus = TXN_STATUS.NO_STATE;
  123. public ObjectStore() {
  124. }
  125. public Configuration getConf() {
  126. return hiveConf;
  127. }
  128. /**
  129. * Called whenever this object is instantiated using ReflectionUils, and also
  130. * on connection retries. In cases of connection retries, conf will usually
  131. * contain modified values.
  132. */
  133. @SuppressWarnings("nls")
  134. public void setConf(Configuration conf) {
  135. // Although an instance of ObjectStore is accessed by one thread, there may
  136. // be many threads with ObjectStore instances. So the static variables
  137. // pmf and prop need to be protected with locks.
  138. pmfPropLock.lock();
  139. try {
  140. isInitialized = false;
  141. hiveConf = conf;
  142. Properties propsFromConf = getDataSourceProps(conf);
  143. boolean propsChanged = !propsFromConf.equals(prop);
  144. if (propsChanged) {
  145. pmf = null;
  146. prop = null;
  147. }
  148. assert(!isActiveTransaction());
  149. shutdown();
  150. // Always want to re-create pm as we don't know if it were created by the
  151. // most recent instance of the pmf
  152. pm = null;
  153. openTrasactionCalls = 0;
  154. currentTransaction = null;
  155. transactionStatus = TXN_STATUS.NO_STATE;
  156. initialize(propsFromConf);
  157. if (!isInitialized) {
  158. throw new RuntimeException(
  159. "Unable to create persistence manager. Check dss.log for details");
  160. } else {
  161. LOG.info("Initialized ObjectStore");
  162. }
  163. } finally {
  164. pmfPropLock.unlock();
  165. }
  166. }
  167. private ClassLoader classLoader;
  168. {
  169. classLoader = Thread.currentThread().getContextClassLoader();
  170. if (classLoader == null) {
  171. classLoader = ObjectStore.class.getClassLoader();
  172. }
  173. }
  174. @SuppressWarnings("nls")
  175. private void initialize(Properties dsProps) {
  176. LOG.info("ObjectStore, initialize called");
  177. prop = dsProps;
  178. pm = getPersistenceManager();
  179. isInitialized = pm != null;
  180. return;
  181. }
  182. /**
  183. * Properties specified in hive-default.xml override the properties specified
  184. * in jpox.properties.
  185. */
  186. @SuppressWarnings("nls")
  187. private static Properties getDataSourceProps(Configuration conf) {
  188. Properties prop = new Properties();
  189. Iterator<Map.Entry<String, String>> iter = conf.iterator();
  190. while (iter.hasNext()) {
  191. Map.Entry<String, String> e = iter.next();
  192. if (e.getKey().contains("datanucleus") || e.getKey().contains("jdo")) {
  193. Object prevVal = prop.setProperty(e.getKey(), conf.get(e.getKey()));
  194. if (LOG.isDebugEnabled()
  195. && !e.getKey().equals(HiveConf.ConfVars.METASTOREPWD.varname)) {
  196. LOG.debug("Overriding " + e.getKey() + " value " + prevVal
  197. + " from jpox.properties with " + e.getValue());
  198. }
  199. }
  200. }
  201. if (LOG.isDebugEnabled()) {
  202. for (Entry<Object, Object> e : prop.entrySet()) {
  203. if (!e.getKey().equals(HiveConf.ConfVars.METASTOREPWD.varname)) {
  204. LOG.debug(e.getKey() + " = " + e.getValue());
  205. }
  206. }
  207. }
  208. return prop;
  209. }
  210. private static PersistenceManagerFactory getPMF() {
  211. if (pmf == null) {
  212. pmf = JDOHelper.getPersistenceManagerFactory(prop);
  213. DataStoreCache dsc = pmf.getDataStoreCache();
  214. if (dsc != null) {
  215. HiveConf conf = new HiveConf(ObjectStore.class);
  216. String objTypes = HiveConf.getVar(conf, HiveConf.ConfVars.METASTORE_CACHE_PINOBJTYPES);
  217. LOG.info("Setting MetaStore object pin classes with hive.metastore.cache.pinobjtypes=\"" + objTypes + "\"");
  218. if (objTypes != null && objTypes.length() > 0) {
  219. objTypes = objTypes.toLowerCase();
  220. String[] typeTokens = objTypes.split(",");
  221. for (String type : typeTokens) {
  222. type = type.trim();
  223. if (PINCLASSMAP.containsKey(type)) {
  224. dsc.pinAll(true, PINCLASSMAP.get(type));
  225. }
  226. else {
  227. LOG.warn(type + " is not one of the pinnable object types: " + org.apache.commons.lang.StringUtils.join(PINCLASSMAP.keySet(), " "));
  228. }
  229. }
  230. }
  231. } else {
  232. LOG.warn("PersistenceManagerFactory returned null DataStoreCache object. Unable to initialize object pin types defined by hive.metastore.cache.pinobjtypes");
  233. }
  234. }
  235. return pmf;
  236. }
  237. private PersistenceManager getPersistenceManager() {
  238. return getPMF().getPersistenceManager();
  239. }
  240. public void shutdown() {
  241. if (pm != null) {
  242. pm.close();
  243. }
  244. }
  245. /**
  246. * Opens a new one or the one already created Every call of this function must
  247. * have corresponding commit or rollback function call
  248. *
  249. * @return an active transaction
  250. */
  251. public boolean openTransaction() {
  252. openTrasactionCalls++;
  253. if (openTrasactionCalls == 1) {
  254. currentTransaction = pm.currentTransaction();
  255. currentTransaction.begin();
  256. transactionStatus = TXN_STATUS.OPEN;
  257. } else {
  258. // something is wrong since openTransactionCalls is greater than 1 but
  259. // currentTransaction is not active
  260. assert ((currentTransaction != null) && (currentTransaction.isActive()));
  261. }
  262. return currentTransaction.isActive();
  263. }
  264. /**
  265. * if this is the commit of the first open call then an actual commit is
  266. * called.
  267. *
  268. * @return Always returns true
  269. */
  270. @SuppressWarnings("nls")
  271. public boolean commitTransaction() {
  272. if (TXN_STATUS.ROLLBACK == transactionStatus) {
  273. return false;
  274. }
  275. if (openTrasactionCalls <= 0) {
  276. throw new RuntimeException("commitTransaction was called but openTransactionCalls = "
  277. + openTrasactionCalls + ". This probably indicates that there are unbalanced " +
  278. "calls to openTransaction/commitTransaction");
  279. }
  280. if (!currentTransaction.isActive()) {
  281. throw new RuntimeException(
  282. "Commit is called, but transaction is not active. Either there are"
  283. + " mismatching open and close calls or rollback was called in the same trasaction");
  284. }
  285. openTrasactionCalls--;
  286. if ((openTrasactionCalls == 0) && currentTransaction.isActive()) {
  287. transactionStatus = TXN_STATUS.COMMITED;
  288. currentTransaction.commit();
  289. }
  290. return true;
  291. }
  292. /**
  293. * @return true if there is an active transaction. If the current transaction
  294. * is either committed or rolled back it returns false
  295. */
  296. public boolean isActiveTransaction() {
  297. if (currentTransaction == null) {
  298. return false;
  299. }
  300. return currentTransaction.isActive();
  301. }
  302. /**
  303. * Rolls back the current transaction if it is active
  304. */
  305. public void rollbackTransaction() {
  306. if (openTrasactionCalls < 1) {
  307. return;
  308. }
  309. openTrasactionCalls = 0;
  310. if (currentTransaction.isActive()
  311. && transactionStatus != TXN_STATUS.ROLLBACK) {
  312. transactionStatus = TXN_STATUS.ROLLBACK;
  313. // could already be rolled back
  314. currentTransaction.rollback();
  315. }
  316. }
  317. public void createDatabase(Database db) throws InvalidObjectException, MetaException {
  318. boolean commited = false;
  319. MDatabase mdb = new MDatabase();
  320. mdb.setName(db.getName().toLowerCase());
  321. mdb.setLocationUri(db.getLocationUri());
  322. mdb.setDescription(db.getDescription());
  323. mdb.setParameters(db.getParameters());
  324. try {
  325. openTransaction();
  326. pm.makePersistent(mdb);
  327. commited = commitTransaction();
  328. } finally {
  329. if (!commited) {
  330. rollbackTransaction();
  331. }
  332. }
  333. }
  334. @SuppressWarnings("nls")
  335. private MDatabase getMDatabase(String name) throws NoSuchObjectException {
  336. MDatabase mdb = null;
  337. boolean commited = false;
  338. try {
  339. openTransaction();
  340. name = name.toLowerCase().trim();
  341. Query query = pm.newQuery(MDatabase.class, "name == dbname");
  342. query.declareParameters("java.lang.String dbname");
  343. query.setUnique(true);
  344. mdb = (MDatabase) query.execute(name);
  345. pm.retrieve(mdb);
  346. commited = commitTransaction();
  347. } finally {
  348. if (!commited) {
  349. rollbackTransaction();
  350. }
  351. }
  352. if (mdb == null) {
  353. throw new NoSuchObjectException("There is no database named " + name);
  354. }
  355. return mdb;
  356. }
  357. public Database getDatabase(String name) throws NoSuchObjectException {
  358. MDatabase mdb = null;
  359. boolean commited = false;
  360. try {
  361. openTransaction();
  362. mdb = getMDatabase(name);
  363. commited = commitTransaction();
  364. } finally {
  365. if (!commited) {
  366. rollbackTransaction();
  367. }
  368. }
  369. Database db = new Database();
  370. db.setName(mdb.getName());
  371. db.setDescription(mdb.getDescription());
  372. db.setLocationUri(mdb.getLocationUri());
  373. db.setParameters(mdb.getParameters());
  374. return db;
  375. }
  376. /**
  377. * Alter the database object in metastore. Currently only the parameters
  378. * of the database can be changed.
  379. * @param dbName the database name
  380. * @param db the Hive Database object
  381. * @throws MetaException
  382. * @throws NoSuchObjectException
  383. */
  384. public boolean alterDatabase(String dbName, Database db)
  385. throws MetaException, NoSuchObjectException {
  386. MDatabase mdb = null;
  387. boolean committed = false;
  388. try {
  389. mdb = getMDatabase(dbName);
  390. // currently only allow changing database parameters
  391. mdb.setParameters(db.getParameters());
  392. openTransaction();
  393. pm.makePersistent(mdb);
  394. committed = commitTransaction();
  395. } finally {
  396. if (!committed) {
  397. rollbackTransaction();
  398. return false;
  399. }
  400. }
  401. return true;
  402. }
  403. public boolean dropDatabase(String dbname) throws NoSuchObjectException, MetaException {
  404. boolean success = false;
  405. LOG.info("Dropping database " + dbname + " along with all tables");
  406. dbname = dbname.toLowerCase();
  407. try {
  408. openTransaction();
  409. // first drop tables
  410. for (String tableName : getAllTables(dbname)) {
  411. dropTable(dbname, tableName);
  412. }
  413. // then drop the database
  414. MDatabase db = getMDatabase(dbname);
  415. pm.retrieve(db);
  416. if (db != null) {
  417. List<MDBPrivilege> dbGrants = this.listDatabaseGrants(dbname);
  418. if (dbGrants != null && dbGrants.size() > 0) {
  419. pm.deletePersistentAll(dbGrants);
  420. }
  421. pm.deletePersistent(db);
  422. }
  423. success = commitTransaction();
  424. } finally {
  425. if (!success) {
  426. rollbackTransaction();
  427. }
  428. }
  429. return success;
  430. }
  431. public List<String> getDatabases(String pattern) throws MetaException {
  432. boolean commited = false;
  433. List<String> databases = null;
  434. try {
  435. openTransaction();
  436. // Take the pattern and split it on the | to get all the composing
  437. // patterns
  438. String[] subpatterns = pattern.trim().split("\\|");
  439. String query = "select name from org.apache.hadoop.hive.metastore.model.MDatabase where (";
  440. boolean first = true;
  441. for (String subpattern : subpatterns) {
  442. subpattern = "(?i)" + subpattern.replaceAll("\\*", ".*");
  443. if (!first) {
  444. query = query + " || ";
  445. }
  446. query = query + " name.matches(\"" + subpattern + "\")";
  447. first = false;
  448. }
  449. query = query + ")";
  450. Query q = pm.newQuery(query);
  451. q.setResult("name");
  452. q.setOrdering("name ascending");
  453. Collection names = (Collection) q.execute();
  454. databases = new ArrayList<String>();
  455. for (Iterator i = names.iterator(); i.hasNext();) {
  456. databases.add((String) i.next());
  457. }
  458. commited = commitTransaction();
  459. } finally {
  460. if (!commited) {
  461. rollbackTransaction();
  462. }
  463. }
  464. return databases;
  465. }
  466. public List<String> getAllDatabases() throws MetaException {
  467. return getDatabases(".*");
  468. }
  469. private MType getMType(Type type) {
  470. List<MFieldSchema> fields = new ArrayList<MFieldSchema>();
  471. if (type.getFields() != null) {
  472. for (FieldSchema field : type.getFields()) {
  473. fields.add(new MFieldSchema(field.getName(), field.getType(), field
  474. .getComment()));
  475. }
  476. }
  477. return new MType(type.getName(), type.getType1(), type.getType2(), fields);
  478. }
  479. private Type getType(MType mtype) {
  480. List<FieldSchema> fields = new ArrayList<FieldSchema>();
  481. if (mtype.getFields() != null) {
  482. for (MFieldSchema field : mtype.getFields()) {
  483. fields.add(new FieldSchema(field.getName(), field.getType(), field
  484. .getComment()));
  485. }
  486. }
  487. Type ret = new Type();
  488. ret.setName(mtype.getName());
  489. ret.setType1(mtype.getType1());
  490. ret.setType2(mtype.getType2());
  491. ret.setFields(fields);
  492. return ret;
  493. }
  494. public boolean createType(Type type) {
  495. boolean success = false;
  496. MType mtype = getMType(type);
  497. boolean commited = false;
  498. try {
  499. openTransaction();
  500. pm.makePersistent(mtype);
  501. commited = commitTransaction();
  502. success = true;
  503. } finally {
  504. if (!commited) {
  505. rollbackTransaction();
  506. }
  507. }
  508. return success;
  509. }
  510. public Type getType(String typeName) {
  511. Type type = null;
  512. boolean commited = false;
  513. try {
  514. openTransaction();
  515. Query query = pm.newQuery(MType.class, "name == typeName");
  516. query.declareParameters("java.lang.String typeName");
  517. query.setUnique(true);
  518. MType mtype = (MType) query.execute(typeName.trim());
  519. pm.retrieve(type);
  520. if (mtype != null) {
  521. type = getType(mtype);
  522. }
  523. commited = commitTransaction();
  524. } finally {
  525. if (!commited) {
  526. rollbackTransaction();
  527. }
  528. }
  529. return type;
  530. }
  531. public boolean dropType(String typeName) {
  532. boolean success = false;
  533. boolean commited = false;
  534. try {
  535. openTransaction();
  536. Query query = pm.newQuery(MType.class, "name == typeName");
  537. query.declareParameters("java.lang.String typeName");
  538. query.setUnique(true);
  539. MType type = (MType) query.execute(typeName.trim());
  540. pm.retrieve(type);
  541. pm.deletePersistent(type);
  542. commited = commitTransaction();
  543. success = true;
  544. } catch (JDOObjectNotFoundException e) {
  545. commited = commitTransaction();
  546. LOG.debug("type not found " + typeName, e);
  547. } finally {
  548. if (!commited) {
  549. rollbackTransaction();
  550. }
  551. }
  552. return success;
  553. }
  554. public void createTable(Table tbl) throws InvalidObjectException, MetaException {
  555. boolean commited = false;
  556. try {
  557. openTransaction();
  558. MTable mtbl = convertToMTable(tbl);
  559. pm.makePersistent(mtbl);
  560. PrincipalPrivilegeSet principalPrivs = tbl.getPrivileges();
  561. List<Object> toPersistPrivObjs = new ArrayList<Object>();
  562. if (principalPrivs != null) {
  563. int now = (int)(System.currentTimeMillis()/1000);
  564. Map<String, List<PrivilegeGrantInfo>> userPrivs = principalPrivs.getUserPrivileges();
  565. putPersistentPrivObjects(mtbl, toPersistPrivObjs, now, userPrivs, PrincipalType.USER);
  566. Map<String, List<PrivilegeGrantInfo>> groupPrivs = principalPrivs.getGroupPrivileges();
  567. putPersistentPrivObjects(mtbl, toPersistPrivObjs, now, groupPrivs, PrincipalType.GROUP);
  568. Map<String, List<PrivilegeGrantInfo>> rolePrivs = principalPrivs.getRolePrivileges();
  569. putPersistentPrivObjects(mtbl, toPersistPrivObjs, now, rolePrivs, PrincipalType.ROLE);
  570. }
  571. pm.makePersistentAll(toPersistPrivObjs);
  572. commited = commitTransaction();
  573. } finally {
  574. if (!commited) {
  575. rollbackTransaction();
  576. }
  577. }
  578. }
  579. /**
  580. * Convert PrivilegeGrantInfo from privMap to MTablePrivilege, and add all of
  581. * them to the toPersistPrivObjs. These privilege objects will be persisted as
  582. * part of createTable.
  583. *
  584. * @param mtbl
  585. * @param toPersistPrivObjs
  586. * @param now
  587. * @param privMap
  588. * @param type
  589. */
  590. private void putPersistentPrivObjects(MTable mtbl, List<Object> toPersistPrivObjs,
  591. int now, Map<String, List<PrivilegeGrantInfo>> privMap, PrincipalType type) {
  592. if (privMap != null) {
  593. for (Map.Entry<String, List<PrivilegeGrantInfo>> entry : privMap
  594. .entrySet()) {
  595. String principalName = entry.getKey();
  596. List<PrivilegeGrantInfo> privs = entry.getValue();
  597. for (int i = 0; i < privs.size(); i++) {
  598. PrivilegeGrantInfo priv = privs.get(i);
  599. if (priv == null) {
  600. continue;
  601. }
  602. MTablePrivilege mTblSec = new MTablePrivilege(
  603. principalName, type.toString(), mtbl, priv.getPrivilege(),
  604. now, priv.getGrantor(), priv.getGrantorType().toString(), priv
  605. .isGrantOption());
  606. toPersistPrivObjs.add(mTblSec);
  607. }
  608. }
  609. }
  610. }
  611. public boolean dropTable(String dbName, String tableName) throws MetaException {
  612. boolean success = false;
  613. try {
  614. openTransaction();
  615. MTable tbl = getMTable(dbName, tableName);
  616. pm.retrieve(tbl);
  617. if (tbl != null) {
  618. // first remove all the partitions
  619. List<MTablePrivilege> tabGrants = listAllTableGrants(dbName, tableName);
  620. if (tabGrants != null && tabGrants.size() > 0) {
  621. pm.deletePersistentAll(tabGrants);
  622. }
  623. List<MTableColumnPrivilege> tblColGrants = listTableAllColumnGrants(dbName,
  624. tableName);
  625. if (tblColGrants != null && tblColGrants.size() > 0) {
  626. pm.deletePersistentAll(tblColGrants);
  627. }
  628. List<MPartitionPrivilege> partGrants = this.listTableAllPartitionGrants(dbName, tableName);
  629. if (partGrants != null && partGrants.size() > 0) {
  630. pm.deletePersistentAll(partGrants);
  631. }
  632. List<MPartitionColumnPrivilege> partColGrants = listTableAllPartitionColumnGrants(dbName,
  633. tableName);
  634. if (partColGrants != null && partColGrants.size() > 0) {
  635. pm.deletePersistentAll(partColGrants);
  636. }
  637. pm.deletePersistentAll(listMPartitions(dbName, tableName, -1));
  638. // then remove the table
  639. pm.deletePersistentAll(tbl);
  640. }
  641. success = commitTransaction();
  642. } finally {
  643. if (!success) {
  644. rollbackTransaction();
  645. }
  646. }
  647. return success;
  648. }
  649. public Table getTable(String dbName, String tableName) throws MetaException {
  650. boolean commited = false;
  651. Table tbl = null;
  652. try {
  653. openTransaction();
  654. tbl = convertToTable(getMTable(dbName, tableName));
  655. commited = commitTransaction();
  656. } finally {
  657. if (!commited) {
  658. rollbackTransaction();
  659. }
  660. }
  661. return tbl;
  662. }
  663. public List<String> getTables(String dbName, String pattern)
  664. throws MetaException {
  665. boolean commited = false;
  666. List<String> tbls = null;
  667. try {
  668. openTransaction();
  669. dbName = dbName.toLowerCase().trim();
  670. // Take the pattern and split it on the | to get all the composing
  671. // patterns
  672. String[] subpatterns = pattern.trim().split("\\|");
  673. String query =
  674. "select tableName from org.apache.hadoop.hive.metastore.model.MTable "
  675. + "where database.name == dbName && (";
  676. boolean first = true;
  677. for (String subpattern : subpatterns) {
  678. subpattern = "(?i)" + subpattern.replaceAll("\\*", ".*");
  679. if (!first) {
  680. query = query + " || ";
  681. }
  682. query = query + " tableName.matches(\"" + subpattern + "\")";
  683. first = false;
  684. }
  685. query = query + ")";
  686. Query q = pm.newQuery(query);
  687. q.declareParameters("java.lang.String dbName");
  688. q.setResult("tableName");
  689. q.setOrdering("tableName ascending");
  690. Collection names = (Collection) q.execute(dbName);
  691. tbls = new ArrayList<String>();
  692. for (Iterator i = names.iterator(); i.hasNext();) {
  693. tbls.add((String) i.next());
  694. }
  695. commited = commitTransaction();
  696. } finally {
  697. if (!commited) {
  698. rollbackTransaction();
  699. }
  700. }
  701. return tbls;
  702. }
  703. public List<String> getAllTables(String dbName) throws MetaException {
  704. return getTables(dbName, ".*");
  705. }
  706. private MTable getMTable(String db, String table) {
  707. MTable mtbl = null;
  708. boolean commited = false;
  709. try {
  710. openTransaction();
  711. db = db.toLowerCase().trim();
  712. table = table.toLowerCase().trim();
  713. Query query = pm.newQuery(MTable.class, "tableName == table && database.name == db");
  714. query.declareParameters("java.lang.String table, java.lang.String db");
  715. query.setUnique(true);
  716. mtbl = (MTable) query.execute(table, db);
  717. pm.retrieve(mtbl);
  718. commited = commitTransaction();
  719. } finally {
  720. if (!commited) {
  721. rollbackTransaction();
  722. }
  723. }
  724. return mtbl;
  725. }
  726. private Table convertToTable(MTable mtbl) throws MetaException {
  727. if (mtbl == null) {
  728. return null;
  729. }
  730. String tableType = mtbl.getTableType();
  731. if (tableType == null) {
  732. // for backwards compatibility with old metastore persistence
  733. if (mtbl.getViewOriginalText() != null) {
  734. tableType = TableType.VIRTUAL_VIEW.toString();
  735. } else if ("TRUE".equals(mtbl.getParameters().get("EXTERNAL"))) {
  736. tableType = TableType.EXTERNAL_TABLE.toString();
  737. } else {
  738. tableType = TableType.MANAGED_TABLE.toString();
  739. }
  740. }
  741. return new Table(mtbl.getTableName(), mtbl.getDatabase().getName(), mtbl
  742. .getOwner(), mtbl.getCreateTime(), mtbl.getLastAccessTime(), mtbl
  743. .getRetention(), convertToStorageDescriptor(mtbl.getSd()),
  744. convertToFieldSchemas(mtbl.getPartitionKeys()), mtbl.getParameters(),
  745. mtbl.getViewOriginalText(), mtbl.getViewExpandedText(),
  746. tableType);
  747. }
  748. private MTable convertToMTable(Table tbl) throws InvalidObjectException,
  749. MetaException {
  750. if (tbl == null) {
  751. return null;
  752. }
  753. MDatabase mdb = null;
  754. try {
  755. mdb = getMDatabase(tbl.getDbName());
  756. } catch (NoSuchObjectException e) {
  757. LOG.error(StringUtils.stringifyException(e));
  758. throw new InvalidObjectException("Database " + tbl.getDbName()
  759. + " doesn't exist.");
  760. }
  761. // If the table has property EXTERNAL set, update table type
  762. // accordingly
  763. String tableType = tbl.getTableType();
  764. boolean isExternal = "TRUE".equals(tbl.getParameters().get("EXTERNAL"));
  765. if (TableType.MANAGED_TABLE.toString().equals(tableType)) {
  766. if (isExternal) {
  767. tableType = TableType.EXTERNAL_TABLE.toString();
  768. }
  769. }
  770. if (TableType.EXTERNAL_TABLE.toString().equals(tableType)) {
  771. if (!isExternal) {
  772. tableType = TableType.MANAGED_TABLE.toString();
  773. }
  774. }
  775. return new MTable(tbl.getTableName().toLowerCase(), mdb,
  776. convertToMStorageDescriptor(tbl.getSd()), tbl.getOwner(), tbl
  777. .getCreateTime(), tbl.getLastAccessTime(), tbl.getRetention(),
  778. convertToMFieldSchemas(tbl.getPartitionKeys()), tbl.getParameters(),
  779. tbl.getViewOriginalText(), tbl.getViewExpandedText(),
  780. tableType);
  781. }
  782. private List<MFieldSchema> convertToMFieldSchemas(List<FieldSchema> keys) {
  783. List<MFieldSchema> mkeys = null;
  784. if (keys != null) {
  785. mkeys = new ArrayList<MFieldSchema>(keys.size());
  786. for (FieldSchema part : keys) {
  787. mkeys.add(new MFieldSchema(part.getName().toLowerCase(),
  788. part.getType(), part.getComment()));
  789. }
  790. }
  791. return mkeys;
  792. }
  793. private List<FieldSchema> convertToFieldSchemas(List<MFieldSchema> mkeys) {
  794. List<FieldSchema> keys = null;
  795. if (mkeys != null) {
  796. keys = new ArrayList<FieldSchema>(mkeys.size());
  797. for (MFieldSchema part : mkeys) {
  798. keys.add(new FieldSchema(part.getName(), part.getType(), part
  799. .getComment()));
  800. }
  801. }
  802. return keys;
  803. }
  804. private List<MOrder> convertToMOrders(List<Order> keys) {
  805. List<MOrder> mkeys = null;
  806. if (keys != null) {
  807. mkeys = new ArrayList<MOrder>(keys.size());
  808. for (Order part : keys) {
  809. mkeys.add(new MOrder(part.getCol().toLowerCase(), part.getOrder()));
  810. }
  811. }
  812. return mkeys;
  813. }
  814. private List<Order> convertToOrders(List<MOrder> mkeys) {
  815. List<Order> keys = null;
  816. if (mkeys != null) {
  817. keys = new ArrayList<Order>();
  818. for (MOrder part : mkeys) {
  819. keys.add(new Order(part.getCol(), part.getOrder()));
  820. }
  821. }
  822. return keys;
  823. }
  824. private SerDeInfo converToSerDeInfo(MSerDeInfo ms) throws MetaException {
  825. if (ms == null) {
  826. throw new MetaException("Invalid SerDeInfo object");
  827. }
  828. return new SerDeInfo(ms.getName(), ms.getSerializationLib(), ms
  829. .getParameters());
  830. }
  831. private MSerDeInfo converToMSerDeInfo(SerDeInfo ms) throws MetaException {
  832. if (ms == null) {
  833. throw new MetaException("Invalid SerDeInfo object");
  834. }
  835. return new MSerDeInfo(ms.getName(), ms.getSerializationLib(), ms
  836. .getParameters());
  837. }
  838. // MSD and SD should be same objects. Not sure how to make then same right now
  839. // MSerdeInfo *& SerdeInfo should be same as well
  840. private StorageDescriptor convertToStorageDescriptor(MStorageDescriptor msd)
  841. throws MetaException {
  842. if (msd == null) {
  843. return null;
  844. }
  845. return new StorageDescriptor(convertToFieldSchemas(msd.getCols()), msd
  846. .getLocation(), msd.getInputFormat(), msd.getOutputFormat(), msd
  847. .isCompressed(), msd.getNumBuckets(), converToSerDeInfo(msd
  848. .getSerDeInfo()), msd.getBucketCols(), convertToOrders(msd
  849. .getSortCols()), msd.getParameters());
  850. }
  851. private MStorageDescriptor convertToMStorageDescriptor(StorageDescriptor sd)
  852. throws MetaException {
  853. if (sd == null) {
  854. return null;
  855. }
  856. return new MStorageDescriptor(convertToMFieldSchemas(sd.getCols()), sd
  857. .getLocation(), sd.getInputFormat(), sd.getOutputFormat(), sd
  858. .isCompressed(), sd.getNumBuckets(), converToMSerDeInfo(sd
  859. .getSerdeInfo()), sd.getBucketCols(),
  860. convertToMOrders(sd.getSortCols()), sd.getParameters());
  861. }
  862. public boolean addPartition(Partition part) throws InvalidObjectException,
  863. MetaException {
  864. boolean success = false;
  865. boolean commited = false;
  866. try {
  867. MTable table = this.getMTable(part.getDbName(), part.getTableName());
  868. List<MTablePrivilege> tabGrants = null;
  869. List<MTableColumnPrivilege> tabColumnGrants = null;
  870. if ("TRUE".equalsIgnoreCase(table.getParameters().get("PARTITION_LEVEL_PRIVILEGE"))) {
  871. tabGrants = this.listAllTableGrants(part
  872. .getDbName(), part.getTableName());
  873. tabColumnGrants = this.listTableAllColumnGrants(
  874. part.getDbName(), part.getTableName());
  875. }
  876. openTransaction();
  877. MPartition mpart = convertToMPart(part);
  878. pm.makePersistent(mpart);
  879. int now = (int)(System.currentTimeMillis()/1000);
  880. List<Object> toPersist = new ArrayList<Object>();
  881. if (tabGrants != null) {
  882. for (MTablePrivilege tab: tabGrants) {
  883. MPartitionPrivilege partGrant = new MPartitionPrivilege(tab
  884. .getPrincipalName(), tab.getPrincipalType(),
  885. mpart, tab.getPrivilege(), now, tab.getGrantor(), tab
  886. .getGrantorType(), tab.getGrantOption());
  887. toPersist.add(partGrant);
  888. }
  889. }
  890. if (tabColumnGrants != null) {
  891. for (MTableColumnPrivilege col : tabColumnGrants) {
  892. MPartitionColumnPrivilege partColumn = new MPartitionColumnPrivilege(col
  893. .getPrincipalName(), col.getPrincipalType(), mpart, col
  894. .getColumnName(), col.getPrivilege(), now, col.getGrantor(), col
  895. .getGrantorType(), col.getGrantOption());
  896. toPersist.add(partColumn);
  897. }
  898. if (toPersist.size() > 0) {
  899. pm.makePersistentAll(toPersist);
  900. }
  901. }
  902. commited = commitTransaction();
  903. success = true;
  904. } finally {
  905. if (!commited) {
  906. rollbackTransaction();
  907. }
  908. }
  909. return success;
  910. }
  911. public Partition getPartition(String dbName, String tableName,
  912. List<String> part_vals) throws NoSuchObjectException, MetaException {
  913. openTransaction();
  914. Partition part = convertToPart(getMPartition(dbName, tableName, part_vals));
  915. commitTransaction();
  916. if(part == null) {
  917. throw new NoSuchObjectException("partition values="
  918. + part_vals.toString());
  919. }
  920. return part;
  921. }
  922. private MPartition getMPartition(String dbName, String tableName,
  923. List<String> part_vals) throws MetaException {
  924. MPartition mpart = null;
  925. boolean commited = false;
  926. try {
  927. openTransaction();
  928. dbName = dbName.toLowerCase().trim();
  929. tableName = tableName.toLowerCase().trim();
  930. MTable mtbl = getMTable(dbName, tableName);
  931. if (mtbl == null) {
  932. commited = commitTransaction();
  933. return null;
  934. }
  935. // Change the query to use part_vals instead of the name which is
  936. // redundant
  937. String name = Warehouse.makePartName(convertToFieldSchemas(mtbl
  938. .getPartitionKeys()), part_vals);
  939. Query query = pm.newQuery(MPartition.class,
  940. "table.tableName == t1 && table.database.name == t2 && partitionName == t3");
  941. query.declareParameters("java.lang.String t1, java.lang.String t2, java.lang.String t3");
  942. query.setUnique(true);
  943. mpart = (MPartition) query.execute(tableName, dbName, name);
  944. pm.retrieve(mpart);
  945. commited = commitTransaction();
  946. } finally {
  947. if (!commited) {
  948. rollbackTransaction();
  949. }
  950. }
  951. return mpart;
  952. }
  953. private MPartition convertToMPart(Partition part)
  954. throws InvalidObjectException, MetaException {
  955. if (part == null) {
  956. return null;
  957. }
  958. MTable mt = getMTable(part.getDbName(), part.getTableName());
  959. if (mt == null) {
  960. throw new InvalidObjectException(
  961. "Partition doesn't have a valid table or database name");
  962. }
  963. return new MPartition(Warehouse.makePartName(convertToFieldSchemas(mt
  964. .getPartitionKeys()), part.getValues()), mt, part.getValues(), part
  965. .getCreateTime(), part.getLastAccessTime(),
  966. convertToMStorageDescriptor(part.getSd()), part.getParameters());
  967. }
  968. private Partition convertToPart(MPartition mpart) throws MetaException {
  969. if (mpart == null) {
  970. return null;
  971. }
  972. return new Partition(mpart.getValues(), mpart.getTable().getDatabase()
  973. .getName(), mpart.getTable().getTableName(), mpart.getCreateTime(),
  974. mpart.getLastAccessTime(), convertToStorageDescriptor(mpart.getSd()),
  975. mpart.getParameters());
  976. }
  977. public boolean dropPartition(String dbName, String tableName,
  978. List<String> part_vals) throws MetaException {
  979. boolean success = false;
  980. try {
  981. openTransaction();
  982. MPartition part = getMPartition(dbName, tableName, part_vals);
  983. if (part != null) {
  984. List<MFieldSchema> schemas = part.getTable().getPartitionKeys();
  985. List<String> colNames = new ArrayList<String>();
  986. for (MFieldSchema col: schemas) {
  987. colNames.add(col.getName());
  988. }
  989. String partName = FileUtils.makePartName(colNames, part_vals);
  990. List<MPartitionPrivilege> partGrants = listPartitionGrants(
  991. dbName, tableName, partName);
  992. if (partGrants != null && partGrants.size() > 0) {
  993. pm.deletePersistentAll(partGrants);
  994. }
  995. List<MPartitionColumnPrivilege> partColumnGrants = listPartitionAllColumnGrants(
  996. dbName, tableName, partName);
  997. if (partColumnGrants != null && partColumnGrants.size() > 0) {
  998. pm.deletePersistentAll(partColumnGrants);
  999. }
  1000. pm.deletePersistent(part);
  1001. }
  1002. success = commitTransaction();
  1003. } finally {
  1004. if (!success) {
  1005. rollbackTransaction();
  1006. }
  1007. }
  1008. return success;
  1009. }
  1010. public List<Partition> getPartitions(String dbName, String tableName, int max)
  1011. throws MetaException {
  1012. openTransaction();
  1013. List<Partition> parts = convertToParts(listMPartitions(dbName, tableName,
  1014. max));
  1015. commitTransaction();
  1016. return parts;
  1017. }
  1018. @Override
  1019. public List<Partition> getPartitionsWithAuth(String dbName, String tblName,
  1020. short maxParts, String userName, List<String> groupNames)
  1021. throws MetaException, NoSuchObjectException, InvalidObjectException {
  1022. boolean success = false;
  1023. try {
  1024. openTransaction();
  1025. List<MPartition> mparts = listMPartitions(dbName, tblName, maxParts);
  1026. List<Partition> parts = new ArrayList<Partition>(mparts.size());
  1027. if (mparts != null && mparts.size()>0) {
  1028. for (MPartition mpart : mparts) {
  1029. MTable mtbl = mpart.getTable();
  1030. Partition part = convertToPart(mpart);
  1031. parts.add(part);
  1032. if ("TRUE".equalsIgnoreCase(mtbl.getParameters().get("PARTITION_LEVEL_PRIVILEGE"))) {
  1033. String partName = Warehouse.makePartName(this.convertToFieldSchemas(mtbl
  1034. .getPartitionKeys()), part.getValues());
  1035. PrincipalPrivilegeSet partAuth = this.getPartitionPrivilegeSet(dbName,
  1036. tblName, partName, userName, groupNames);
  1037. part.setPrivileges(partAuth);
  1038. }
  1039. }
  1040. }
  1041. success = commitTransaction();
  1042. return parts;
  1043. } finally {
  1044. if (!success) {
  1045. rollbackTransaction();
  1046. }
  1047. }
  1048. }
  1049. @Override
  1050. public Partition getPartitionWithAuth(String dbName, String tblName,
  1051. List<String> partVals, String user_name, List<String> group_names)
  1052. throws NoSuchObjectException, MetaException, InvalidObjectException {
  1053. boolean success = false;
  1054. try {
  1055. openTransaction();
  1056. MPartition mpart = getMPartition(dbName, tblName, partVals);
  1057. if (mpart == null) {
  1058. commitTransaction();
  1059. throw new NoSuchObjectException("partition values="
  1060. + partVals.toString());
  1061. }
  1062. Partition part = null;
  1063. MTable mtbl = mpart.getTable();
  1064. part = convertToPart(mpart);
  1065. if ("TRUE".equalsIgnoreCase(mtbl.getParameters().get("PARTITION_LEVEL_PRIVILEGE"))) {
  1066. String partName = Warehouse.makePartName(this.convertToFieldSchemas(mtbl
  1067. .getPartitionKeys()), partVals);
  1068. PrincipalPrivilegeSet partAuth = this.getPartitionPrivilegeSet(dbName,
  1069. tblName, partName, user_name, group_names);
  1070. part.setPrivileges(partAuth);
  1071. }
  1072. success = commitTransaction();
  1073. return part;
  1074. } finally {
  1075. if (!success) {
  1076. rollbackTransaction();
  1077. }
  1078. }
  1079. }
  1080. private List<Partition> convertToParts(List<MPartition> mparts)
  1081. throws MetaException {
  1082. List<Partition> parts = new ArrayList<Partition>(mparts.size());
  1083. for (MPartition mp : mparts) {
  1084. parts.add(convertToPart(mp));
  1085. }
  1086. return parts;
  1087. }
  1088. // TODO:pc implement max
  1089. public List<String> listPartitionNames(String dbName, String tableName,
  1090. short max) throws MetaException {
  1091. List<String> pns = new ArrayList<String>();
  1092. boolean success = false;
  1093. try {
  1094. openTransaction();
  1095. LOG.debug("Executing getPartitionNames");
  1096. dbName = dbName.toLowerCase().trim();
  1097. tableName = tableName.toLowerCase().trim();
  1098. Query q = pm.newQuery(
  1099. "select partitionName from org.apache.hadoop.hive.metastore.model.MPartition "
  1100. + "where table.database.name == t1 && table.tableName == t2 "
  1101. + "order by partitionName asc");
  1102. q.declareParameters("java.lang.String t1, java.lang.String t2");
  1103. q.setResult("partitionName");
  1104. Collection names = (Collection) q.execute(dbName, tableName);
  1105. pns = new ArrayList<String>();
  1106. for (Iterator i = names.iterator(); i.hasNext();) {
  1107. pns.add((String) i.next());
  1108. }
  1109. success = commitTransaction();
  1110. } finally {
  1111. if (!success) {
  1112. rollbackTransaction();
  1113. }
  1114. }
  1115. return pns;
  1116. }
  1117. // TODO:pc implement max
  1118. private List<MPartition> listMPartitions(String dbName, String tableName,
  1119. int max) {
  1120. boolean success = false;
  1121. List<MPartition> mparts = null;
  1122. try {
  1123. openTransaction();
  1124. LOG.debug("Executing listMPartitions");
  1125. dbName = dbName.toLowerCase().trim();
  1126. tableName = tableName.toLowerCase().trim();
  1127. Query query = pm.newQuery(MPartition.class,
  1128. "table.tableName == t1 && table.database.name == t2");
  1129. query.declareParameters("java.lang.String t1, java.lang.String t2");
  1130. mparts = (List<MPartition>) query.execute(tableName, dbName);
  1131. LOG.debug("Done executing query for listMPartitions");
  1132. pm.retrieveAll(mparts);
  1133. success = commitTransaction();
  1134. LOG.debug("Done retrieving all objects for listMPartitions");
  1135. } finally {
  1136. if (!success) {
  1137. rollbackTransaction();
  1138. }
  1139. }
  1140. return mparts;
  1141. }
  1142. @Override
  1143. public List<Partition> getPartitionsByFilter(String dbName, String tblName,
  1144. String filter, short maxParts) throws MetaException, NoSuchObjectException {
  1145. openTransaction();
  1146. List<Partition> parts = convertToParts(listMPartitionsByFilter(dbName,
  1147. tblName, filter, maxParts));
  1148. commitTransaction();
  1149. return parts;
  1150. }
  1151. private String makeQueryFilterString(MTable mtable, String filter,
  1152. Map<String, String> params)
  1153. throws MetaException {
  1154. StringBuilder queryBuilder = new StringBuilder(
  1155. "table.tableName == t1 && table.database.name == t2");
  1156. if( filter != null && filter.length() > 0) {
  1157. Table table = convertToTable(mtable);
  1158. CharStream cs = new ANTLRNoCaseStringStream(filter);
  1159. FilterLexer lexer = new FilterLexer(cs);
  1160. CommonTokenStream tokens = new CommonTokenStream();
  1161. tokens.setTokenSource (lexer);
  1162. FilterParser parser = new FilterParser(tokens);
  1163. try {
  1164. parser.filter();
  1165. } catch(RecognitionException re) {
  1166. throw new MetaException("Error parsing partition filter : " + re);
  1167. }
  1168. String jdoFilter = parser.tree.generateJDOFilter(table, params);
  1169. if( jdoFilter.trim().length() > 0 ) {
  1170. queryBuilder.append(" && ( ");
  1171. queryBuilder.append(jdoFilter.trim());
  1172. queryBuilder.append(" )");
  1173. }
  1174. }
  1175. return queryBuilder.toString();
  1176. }
  1177. private String makeParameterDeclarationString(Map<String, String> params) {
  1178. //Create the parameter declaration string
  1179. StringBuilder paramDecl = new StringBuilder();
  1180. for(String key : params.keySet() ) {
  1181. paramDecl.append(", java.lang.String " + key);
  1182. }
  1183. return paramDecl.toString();
  1184. }
  1185. private List<MPartition> listMPartitionsByFilter(String dbName, String tableName,
  1186. String filter, short maxParts) throws MetaException, NoSuchObjectException{
  1187. boolean success = false;
  1188. List<MPartition> mparts = null;
  1189. try {
  1190. openTransaction();
  1191. LOG.debug("Executing listMPartitionsByFilter");
  1192. dbName = dbName.toLowerCase();
  1193. tableName = tableName.toLowerCase();
  1194. MTable mtable = getMTable(dbName, tableName);
  1195. if( mtable == null ) {
  1196. throw new NoSuchObjectException("Specified database/table does not exist : "
  1197. + dbName + "." + tableName);
  1198. }
  1199. Map<String, String> params = new HashMap<String, String>();
  1200. String queryFilterString =
  1201. makeQueryFilterString(mtable, filter, params);
  1202. Query query = pm.newQuery(MPartition.class,
  1203. queryFilterString);
  1204. if( maxParts >= 0 ) {
  1205. //User specified a row limit, set it on the Query
  1206. query.setRange(0, maxParts);
  1207. }
  1208. LOG.debug("Filter specified is " + filter + "," +
  1209. " JDOQL filter is " + queryFilterString);
  1210. params.put("t1", tableName.trim());
  1211. params.put("t2", dbName.trim());
  1212. String parameterDeclaration = makeParameterDeclarationString(params);
  1213. query.declareParameters(parameterDeclaration);
  1214. query.setOrdering("partitionName ascending");
  1215. mparts = (List<MPartition>) query.executeWithMap(params);
  1216. LOG.debug("Done executing query for listMPartitionsByFilter");
  1217. pm.retrieveAll(mparts);
  1218. success = commitTransaction();
  1219. LOG.debug("Done retrieving all objects for listMPartitionsByFilter");
  1220. } finally {
  1221. if (!success) {
  1222. rollbackTransaction();
  1223. }
  1224. }
  1225. return mparts;
  1226. }
  1227. @Override
  1228. public List<String> listPartitionNamesByFilter(String dbName, String tableName,
  1229. String filter, short maxParts) throws MetaException {
  1230. boolean success = false;
  1231. List<String> partNames = new ArrayList<String>();
  1232. try {
  1233. openTransaction();
  1234. LOG.debug("Executing listMPartitionsByFilter");
  1235. dbName = dbName.toLowerCase();
  1236. tableName = tableName.toLowerCase();
  1237. MTable mtable = getMTable(dbName, tableName);
  1238. if( mtable == null ) {
  1239. // To be consistent with the behavior of listPartitionNames, if the
  1240. // table or db does not exist, we return an empty list
  1241. return partNames;
  1242. }
  1243. Map<String, String> params = new HashMap<String, String>();
  1244. String queryFilterString =
  1245. makeQueryFilterString(mtable, filter, params);
  1246. Query query = pm.newQuery(
  1247. "select partitionName from org.apache.hadoop.hive.metastore.model.MPartition "
  1248. + "where " + queryFilterString);
  1249. if( maxParts >= 0 ) {
  1250. //User specified a row limit, set it on the Query
  1251. query.setRange(0, maxParts);
  1252. }
  1253. LOG.debug("Filter specified is " + filter + "," +
  1254. " JDOQL filter is " + queryFilterString);
  1255. LOG.debug("Parms is " + params);
  1256. params.put("t1", tableName.trim());
  1257. params.put("t2", dbName.trim());
  1258. String parameterDeclaration = makeParameterDeclarationString(params);
  1259. query.declareParameters(parameterDeclaration);
  1260. query.setOrdering("partitionName ascending");
  1261. query.setResult("partitionName");
  1262. Collection names = (Collection) query.executeWithMap(params);
  1263. partNames = new ArrayList<String>();
  1264. for (Iterator i = names.iterator(); i.hasNext();) {
  1265. partNames.add((String) i.next());
  1266. }
  1267. LOG.debug("Done executing query for listMPartitionNamesByFilter");
  1268. success = commitTransaction();
  1269. LOG.debug("Done retrieving all objects for listMPartitionNamesByFilter");
  1270. } finally {
  1271. if (!success) {
  1272. rollbackTransaction();
  1273. }
  1274. }
  1275. return partNames;
  1276. }
  1277. public void alterTable(String dbname, String name, Table newTable)
  1278. throws InvalidObjectException, MetaException {
  1279. boolean success = false;
  1280. try {
  1281. openTransaction();
  1282. name = name.toLowerCase();
  1283. dbname = dbname.toLowerCase();
  1284. MTable newt = convertToMTable(newTable);
  1285. if (newt == null) {
  1286. throw new InvalidObjectException("new table is invalid");
  1287. }
  1288. MTable oldt = getMTable(dbname, name);
  1289. if (oldt == null) {
  1290. throw new MetaException("table " + name + " doesn't exist");
  1291. }
  1292. // For now only alter name, owner, paramters, cols, bucketcols are allowed
  1293. oldt.setTableName(newt.getTableName().toLowerCase());
  1294. oldt.setParameters(newt.getParameters());
  1295. oldt.setOwner(newt.getOwner());
  1296. oldt.setSd(newt.getSd());
  1297. oldt.setDatabase(newt.getDatabase());
  1298. oldt.setRetention(newt.getRetention());
  1299. oldt.setPartitionKeys(newt.getPartitionKeys());
  1300. oldt.setTableType(newt.getTableType());
  1301. oldt.setLastAccessTime(newt.getLastAccessTime());
  1302. // commit the changes
  1303. success = commitTransaction();
  1304. } finally {
  1305. if (!success) {
  1306. rollbackTransaction();
  1307. }
  1308. }
  1309. }
  1310. public void alterIndex(String dbname, String baseTblName, String name, Index newIndex)
  1311. throws InvalidObjectException, MetaException {
  1312. boolean success = false;
  1313. try {
  1314. openTransaction();
  1315. name = name.toLowerCase();
  1316. baseTblName = baseTblName.toLowerCase();
  1317. dbname = dbname.toLowerCase();
  1318. MIndex newi = convertToMIndex(newIndex);
  1319. if (newi == null) {
  1320. throw new InvalidObjectException("new index is invalid");
  1321. }
  1322. MIndex oldi = getMIndex(dbname, baseTblName, name);
  1323. if (oldi == null) {
  1324. throw new MetaException("index " + name + " doesn't exist");
  1325. }
  1326. // For now only alter paramters are allowed
  1327. oldi.setParameters(newi.getParameters());
  1328. // commit the changes
  1329. success = commitTransaction();
  1330. } finally {
  1331. if (!success) {
  1332. rollbackTransaction();
  1333. }
  1334. }
  1335. }
  1336. publi

Large files files are truncated, but you can click here to view the full file