Data and AI Platforms

Hive DROP TABLE hangs on a PostgreSQL metastore and how to fix it

By
On some older Hive deployments with PostgreSQL as the metastore database, DROP TABLE can hang while PostgreSQL shows UPDATE locks on metastore tables. This often happens when certain privilege tables and indexes were not created correctly during an upgrade or manual schema setup. This note shows a legacy DDL patch you can apply to add the missing tables and indexes so DROP TABLE completes successfully again. It also covers why Hive needs an external metastore instead of embedded Derby, and walks through a MySQL metastore setup: my.cnf, database and user, hive-site.xml, driver distribution, schema check and schema upgrades. Always back up your metastore before running any DDL.

Important legacy note: The SQL below matches a specific generation of the Hive metastore schema from around 2013. You should only apply it if you have confirmed that these tables and indexes are missing in your metastore and that the definitions match your Hive version. Always test on a non-production copy of your metastore first.

Symptom

When using PostgreSQL as the Hive metastore database, a statement like:

DROP TABLE xyz;

may hang indefinitely. On the PostgreSQL side, you see long-running transactions and locks with UPDATE operations on metastore tables, even though no obvious workload is active.

This can be caused by missing indexes and privilege tables that Hive expects to exist. Without them, metadata operations (including DROP TABLE) can block or fail.

DDL patch for missing Hive metastore tables and indexes (PostgreSQL)

The following SQL creates the missing indexes on IDXS and the privilege/role-related tables and indexes. Run it against your metastore database from the psql CLI, connected as the Hive metastore user.

-- Indexes on IDXS
CREATE INDEX "IDXS_FK1" ON "IDXS" USING btree ("SD_ID");
CREATE INDEX "IDXS_FK2" ON "IDXS" USING btree ("INDEX_TBL_ID");
CREATE INDEX "IDXS_FK3" ON "IDXS" USING btree ("ORIG_TBL_ID");

-- ROLES table
CREATE TABLE "ROLES" (
  "ROLE_ID"      bigint      NOT NULL,
  "CREATE_TIME"  int         NOT NULL,
  "OWNER_NAME"   varchar(128) DEFAULT NULL,
  "ROLE_NAME"    varchar(128) DEFAULT NULL,
  PRIMARY KEY ("ROLE_ID"),
  CONSTRAINT "ROLEENTITYINDEX" UNIQUE ("ROLE_NAME")
);

-- ROLE_MAP table
CREATE TABLE "ROLE_MAP" (
  "ROLE_GRANT_ID" bigint      NOT NULL,
  "ADD_TIME"      int         NOT NULL,
  "GRANT_OPTION"  smallint    NOT NULL,
  "GRANTOR"       varchar(128) DEFAULT NULL,
  "GRANTOR_TYPE"  varchar(128) DEFAULT NULL,
  "PRINCIPAL_NAME" varchar(128) DEFAULT NULL,
  "PRINCIPAL_TYPE" varchar(128) DEFAULT NULL,
  "ROLE_ID"        bigint      DEFAULT NULL,
  PRIMARY KEY ("ROLE_GRANT_ID"),
  CONSTRAINT "USERROLEMAPINDEX"
    UNIQUE ("PRINCIPAL_NAME","ROLE_ID","GRANTOR","GRANTOR_TYPE"),
  CONSTRAINT "ROLE_MAP_FK1"
    FOREIGN KEY ("ROLE_ID") REFERENCES "ROLES" ("ROLE_ID")
);

-- GLOBAL_PRIVS table
CREATE TABLE "GLOBAL_PRIVS" (
  "USER_GRANT_ID"   bigint      NOT NULL,
  "CREATE_TIME"     int         NOT NULL,
  "GRANT_OPTION"    smallint    NOT NULL,
  "GRANTOR"         varchar(128) DEFAULT NULL,
  "GRANTOR_TYPE"    varchar(128) DEFAULT NULL,
  "PRINCIPAL_NAME"  varchar(128) DEFAULT NULL,
  "PRINCIPAL_TYPE"  varchar(128) DEFAULT NULL,
  "USER_PRIV"       varchar(128) DEFAULT NULL,
  PRIMARY KEY ("USER_GRANT_ID"),
  CONSTRAINT "GLOBALPRIVILEGEINDEX"
    UNIQUE ("PRINCIPAL_NAME","PRINCIPAL_TYPE","USER_PRIV","GRANTOR","GRANTOR_TYPE")
);

-- DB_PRIVS table
CREATE TABLE "DB_PRIVS" (
  "DB_GRANT_ID"    bigint      NOT NULL,
  "CREATE_TIME"    int         NOT NULL,
  "DB_ID"          bigint      DEFAULT NULL,
  "GRANT_OPTION"   smallint    NOT NULL,
  "GRANTOR"        varchar(128) DEFAULT NULL,
  "GRANTOR_TYPE"   varchar(128) DEFAULT NULL,
  "PRINCIPAL_NAME" varchar(128) DEFAULT NULL,
  "PRINCIPAL_TYPE" varchar(128) DEFAULT NULL,
  "DB_PRIV"        varchar(128) DEFAULT NULL,
  PRIMARY KEY ("DB_GRANT_ID"),
  CONSTRAINT "DBPRIVILEGEINDEX"
    UNIQUE ("DB_ID","PRINCIPAL_NAME","PRINCIPAL_TYPE",
            "DB_PRIV","GRANTOR","GRANTOR_TYPE"),
  CONSTRAINT "DB_PRIVS_FK1"
    FOREIGN KEY ("DB_ID") REFERENCES "DBS" ("DB_ID")
);

-- PART_PRIVS table
CREATE TABLE "PART_PRIVS" (
  "PART_GRANT_ID"  bigint      NOT NULL,
  "CREATE_TIME"    int         NOT NULL,
  "GRANT_OPTION"   smallint    NOT NULL,
  "GRANTOR"        varchar(128) DEFAULT NULL,
  "GRANTOR_TYPE"   varchar(128) DEFAULT NULL,
  "PART_ID"        bigint      DEFAULT NULL,
  "PRINCIPAL_NAME" varchar(128) DEFAULT NULL,
  "PRINCIPAL_TYPE" varchar(128) DEFAULT NULL,
  "PART_PRIV"      varchar(128) DEFAULT NULL,
  PRIMARY KEY ("PART_GRANT_ID"),
  CONSTRAINT "PART_PRIVS_FK1"
    FOREIGN KEY ("PART_ID") REFERENCES "PARTITIONS" ("PART_ID")
);

CREATE INDEX "PARTPRIVILEGEINDEX"
  ON "PART_PRIVS"
  USING btree ("PART_ID","PRINCIPAL_NAME","PRINCIPAL_TYPE",
               "PART_PRIV","GRANTOR","GRANTOR_TYPE");

-- PART_COL_PRIVS table
CREATE TABLE "PART_COL_PRIVS" (
  "PART_COLUMN_GRANT_ID" bigint      NOT NULL,
  "COLUMN_NAME"          varchar(128) DEFAULT NULL,
  "CREATE_TIME"          int          NOT NULL,
  "GRANT_OPTION"         smallint     NOT NULL,
  "GRANTOR"              varchar(128) DEFAULT NULL,
  "GRANTOR_TYPE"         varchar(128) DEFAULT NULL,
  "PART_ID"              bigint       DEFAULT NULL,
  "PRINCIPAL_NAME"       varchar(128) DEFAULT NULL,
  "PRINCIPAL_TYPE"       varchar(128) DEFAULT NULL,
  "PART_COL_PRIV"        varchar(128) DEFAULT NULL,
  PRIMARY KEY ("PART_COLUMN_GRANT_ID"),
  CONSTRAINT "PART_COL_PRIVS_FK1"
    FOREIGN KEY ("PART_ID") REFERENCES "PARTITIONS" ("PART_ID")
);

CREATE INDEX "PARTITIONCOLUMNPRIVILEGEINDEX"
  ON "PART_COL_PRIVS"
  USING btree ("PART_ID","COLUMN_NAME","PRINCIPAL_NAME","PRINCIPAL_TYPE",
               "PART_COL_PRIV","GRANTOR","GRANTOR_TYPE");

How to apply this in PostgreSQL

Connect to your Hive metastore database with psql and paste the DDL:

psql -h <HOSTNAME> -d metastore -U hiveuser -W

After the tables and indexes have been created successfully, retry:

DROP TABLE xyz;

In many legacy setups this resolves the hanging DROP TABLE issue because the metastore schema now matches what Hive expects and PostgreSQL can evaluate privilege and metadata queries efficiently instead of stalling on missing objects.

Reminder: Always dump and back up your metastore before running manual DDL like this, and validate that your Hive version expects these exact table and column names.

Find what is holding the lock in PostgreSQL

Before you run any DDL, check what DROP TABLE is actually waiting for. Often it is not a missing table at all but an old session that never finished its transaction. This query lists sessions in the metastore database that are waiting on a lock or sitting idle inside a transaction, and who blocks them:

SELECT pid, state, wait_event_type,
       now() - xact_start AS xact_age,
       pg_blocking_pids(pid) AS blocked_by,
       left(query, 80) AS query
FROM pg_stat_activity
WHERE datname = 'metastore'
  AND (wait_event_type = 'Lock' OR state = 'idle in transaction');

Change metastore to your database name. pg_blocking_pids needs PostgreSQL 9.6 or newer. If the blocker is a stale session that is idle in a transaction, you can end it with SELECT pg_terminate_backend(<pid>);. Make sure it is not a live metastore call first. If nothing blocks and the hang comes back, compare your schema with a clean one as shown below.

A second cause is a table with a very large number of partitions. Dropping it can take longer than the metastore client timeout, so the client gives up while the database is still busy. Dropping partitions in batches before you drop the table avoids that.

From my own work:

  • I hit this on a cluster with more than 100 nodes, years ago.
  • Most of the time Hive was not the problem. The database under the metastore was holding a lock.

How DROP TABLE works in Hive 3 and 4

The basics have not changed, but newer Hive adds a second layer of locks. Here is what to know if you run Hive 3 or 4 today.

  • One long database transaction. The metastore drops all partitions and then the table inside one transaction in its database. Rows stay locked until it commits. A slow drop blocks other metastore calls on that table, and an old open session blocks the drop.
  • Partitions go in batches. Hive 4 drops partitions in batches of hive.metastore.batch.retrieve.table.partition.max (default 1000). Hive 3.1 and older use hive.metastore.batch.retrieve.max (default 300). Batching keeps memory down, but it is still one transaction.
  • Direct SQL. hive.metastore.try.direct.sql is on by default, so many metastore reads run as plain SQL instead of going through DataNucleus. hive.metastore.direct.sql.batch.size limits the size of those queries for databases that need it, such as Oracle and SQL Server.
  • Hive locks on top. With transactional tables and DbTxnManager, Hive keeps its own locks and transactions in metastore tables such as HIVE_LOCKS, TXNS and TXN_COMPONENTS. DROP TABLE needs an exclusive lock, so it waits for every open query on that table.
  • Check from Hive. Run SHOW LOCKS, SHOW TRANSACTIONS and SHOW COMPACTIONS. A transaction whose client stopped sending heartbeats is aborted after hive.txn.timeout (300 seconds by default). ABORT TRANSACTIONS ends one by hand. See Hive transactions.
  • PostgreSQL. Use the query above. To stop forgotten sessions from holding locks for hours, set idle_in_transaction_session_timeout for the metastore user.
  • MySQL. SELECT * FROM sys.innodb_lock_waits; shows who waits on whom. SHOW ENGINE INNODB STATUS shows the latest deadlock. KILL <id> ends a stuck connection.

Why Hive Needs an External Metastore

The fix above assumes Hive already runs on an external metastore database. By default Hive uses an embedded Derby database. That is fine for local tests, but it allows only one user at a time, has no real HA story and is hard to back up. As soon as several users and services share metadata, you need an external RDBMS. It stores your databases and tables, partitions and storage descriptors, SerDes, column definitions and privileges. PostgreSQL is one option. The other common one is MySQL, and the setup below comes from my original MySQL metastore guide.

Setting Up a MySQL Metastore

MySQL configuration

The original setup used MySQL 5.1+ with InnoDB and binary logging. A simplified /etc/my.cnf:

[mysqld_safe]
socket = /var/lib/mysql/mysql.sock

[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/lib/mysql/mysql.sock
log-error = /var/log/mysqld.log
datadir = /opt/hadoop/mysql

default-storage_engine = InnoDB
skip-bdb = 1
skip_name_resolve

# Timeouts
connect_timeout = 30
wait_timeout = 30
interactive_timeout = 100

# Cache and memory settings (example values)
key_buffer = 128M
thread_concurrency = 4
thread_cache = 16
thread_stack = 256K
table_cache = 512
tmp_table_size = 64M
max_heap_table_size = 64M

# Binary logging for replication or PITR
server-id = 1001
log_bin = /var/log/mysql/mysqlserver-bin.log
expire_logs_days = 3
max_binlog_size = 256M

# InnoDB tuning
innodb_file_per_table = 1
innodb_data_file_path = ibdata1:10M:autoextend
innodb_buffer_pool_size = 512M
innodb_log_file_size = 16M
innodb_flush_log_at_trx_commit = 1

# Slow query logging and query cache (legacy setup)
long_query_time = 2
log_slow_queries = /var/log/mysql/mysql-slow.log
query_cache_size = 64M
query_cache_type = 1
query_cache_limit = 4M

This uses InnoDB as the default engine, binary logs for replication or recovery, and basic memory, cache and slow query settings.

Note: several of these options date from MySQL 5.1 and were renamed or removed in later versions, for example skip-bdb, thread_concurrency, table_cache (now table_open_cache), log_slow_queries (now slow_query_log and slow_query_log_file) and the query cache settings, which MySQL 8.0 removed completely. A current MySQL will refuse to start with them, so treat this file as historical and drop or rename those lines.

Create the metastore database and user

After restarting MySQL (for example service mysqld restart), create a user and database for Hive:

mysql> CREATE USER 'hive'@'%' IDENTIFIED BY 'strong_password';
mysql> GRANT ALL PRIVILEGES ON hive_live.* TO 'hive'@'%' WITH GRANT OPTION;
mysql> CREATE DATABASE hive_live;

This simple privilege model is fine on a dedicated metastore host. In modern setups you would grant tighter privileges and lock down network access.

Point Hive at MySQL

In hive-site.xml:

<property>
  <name>javax.jdo.option.ConnectionURL</name>
  <value>jdbc:mysql://mysqlserver:3306/hive_live?createDatabaseIfNotExist=true</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionDriverName</name>
  <value>com.mysql.jdbc.Driver</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionUserName</name>
  <value>hive</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionPassword</name>
  <value>strong_password</value>
</property>

With Connector/J 8.0 and later, the driver class is com.mysql.cj.jdbc.Driver. The old com.mysql.jdbc.Driver name only works as a deprecated alias.

Distribute the JDBC driver and Hive config

Every node that runs Hive services or clients needs the MySQL Connector/J driver and the same hive-site.xml:

for i in $(cat /etc/hadoop-0.20/conf/slaves); do
  scp -r /usr/lib/hive/lib/mysql-connector-java-5.1.11-bin.jar \
    "$i":/usr/lib/hive/lib/
done
for i in $(cat /etc/hadoop-0.20/conf/slaves); do
  scp -r /etc/hive/conf/hive-* \
    "$i":/etc/hive/conf.dist/
done

Paths differ between distributions, but the idea is the same everywhere.

Check the schema

On the first Hive query, the metastore creates its schema. Check it:

mysql> USE hive_live;
mysql> SHOW TABLES;
+-------------------------+
| Tables_in_hive_live     |
+-------------------------+
| BUCKETING_COLS          |
| COLUMNS                 |
| DATABASE_PARAMS         |
| DBS                     |
| DB_PRIVS                |
| GLOBAL_PRIVS            |
| IDXS                    |
| INDEX_PARAMS            |
| PARTITIONS              |
| PARTITION_KEYS          |
| PARTITION_KEY_VALS      |
| PARTITION_PARAMS        |
| PART_COL_PRIVS          |
| PART_PRIVS              |
| ROLES                   |
| ROLE_MAP                |
| SDS                     |
| SD_PARAMS               |
| SEQUENCE_TABLE          |
| SERDES                  |
| SERDE_PARAMS            |
| SORT_COLS               |
| TABLE_PARAMS            |
| TBLS                    |
| TBL_COL_PRIVS           |
| TBL_PRIVS               |
| TYPES                   |
| TYPE_FIELDS             |
+-------------------------+

Note that the privilege tables (ROLES, ROLE_MAP, GLOBAL_PRIVS, DB_PRIVS, PART_PRIVS, PART_COL_PRIVS) are in this list. Those are the same tables that were missing in the PostgreSQL case above. Comparing your metastore against a clean schema like this is a quick way to spot what an upgrade forgot.

Upgrading the schema

When you upgrade Hive, the metastore schema may need an upgrade too. Hive ships SQL scripts for this, typically under:

/var/lib/hive/metastore/scripts/upgrade/mysql/

Connect and source the right script (example for a historical version):

mysql> USE hive_live;
mysql> SOURCE /var/lib/hive/metastore/scripts/upgrade/mysql/upgrade-0.6.0-to-0.7.0.mysql.sql;

The hive-schema-X.Y.Z.mysql.sql files in the same directory create a fresh schema; the upgrade-A-to-B files upgrade an existing one. Since Hive 0.12 the schematool does this for you:

schematool -dbType mysql -info
schematool -dbType mysql -upgradeSchema

Always take a full database backup first. Whether you run MySQL, PostgreSQL or a managed metastore, the pattern is the same: an external RDBMS for shared metadata, and schema upgrade scripts managed together with your Hive version.

Reference: MySQL Connector/J

Related posts: Hadoop Snappy compression with Hive, fixing the Hive too many counters error, connecting to HiveServer2 with JDBC and Kerberos and Hive on Tez vs Hive on Spark.

Need help with distributed systems, backend engineering or data platforms? See my consulting services.

Alexander Alten

Alexander Alten

Founder of Scalytics, co-creator and PMC member of Apache Wayang, and author of KafScale. I write about Kafka, streaming, data platforms, IoT and AI agent infrastructure in production.