package com.alibaba.druid.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.sql.XAConnection;
import org.postgresql.core.BaseConnection;
import org.postgresql.xa.PGXAConnection;

public class PGUtils {
   private static Set<String> keywords;
   private static final long[] pseudoColumnHashCodes;

   public static XAConnection createXAConnection(Connection physicalConn) throws SQLException {
      return new PGXAConnection((BaseConnection)physicalConn);
   }

   public static List<String> showTables(Connection conn) throws SQLException {
      List<String> tables = new ArrayList();
      Statement stmt = null;
      ResultSet rs = null;

      try {
         stmt = conn.createStatement();
         rs = stmt.executeQuery("SELECT tablename FROM pg_catalog.pg_tables where schemaname not in ('pg_catalog', 'information_schema', 'sys')");

         while(rs.next()) {
            String tableName = rs.getString(1);
            tables.add(tableName);
         }
      } finally {
         JdbcUtils.close(rs);
         JdbcUtils.close(stmt);
      }

      return tables;
   }

   public static boolean isKeyword(String name) {
      if (name == null) {
         return false;
      } else {
         String name_lower = name.toLowerCase();
         Set<String> words = keywords;
         if (words == null) {
            words = new HashSet();
            Utils.loadFromFile("META-INF/druid/parser/postgresql/keywords", words);
            keywords = words;
         }

         return words.contains(name_lower);
      }
   }

   public static boolean isPseudoColumn(long hash) {
      return Arrays.binarySearch(pseudoColumnHashCodes, hash) >= 0;
   }

   static {
      long[] array = new long[]{FnvHash.Constants.CURRENT_TIMESTAMP};
      Arrays.sort(array);
      pseudoColumnHashCodes = array;
   }
}
