-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
176 lines (160 loc) · 5.13 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# Copyright 2012 Alex Breshears.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from java.lang import *
from java.sql import *
import simplejson as json
import csv
import StringIO
import config
def runQueryDirectly(query):
""" Runs a Query via JDBC in Hive and returns a Java result set """
Class.forName(config.HIVE_JDBC_DRIVER_NAME)
conn_string = config.HIVE_CONNECTION_STRING
conn = DriverManager.getConnection(conn_string, "", "")
stmt = conn.createStatement()
result = stmt.executeQuery(query)
return result
def getTableContentsSQL(table, columns=None, limit=None):
""" Generates the SQL required to get full table contents from a Hive Table (most often for results)"""
if not columns:
sql = 'SELECT * FROM %s ' % table
else:
sql = 'SELECT '
for c in columns:
sql += ' %s, ' % c
sql += 'FROM %s ' % table
if limit:
sql += 'LIMIT %s' % limit
return sql
def getTables():
""" Returns an array of strings of all tables in Hive """
toReturn = []
result = runQueryDirectly('SHOW tables')
while result.next():
toReturn.append(result.getString(1))
return toReturn
def tableExists(table):
""" Determines if a table exists in Hive """
return table in getTables()
def getColumnInformation(table, columns=None):
""" Returns a dictionary describing (selected) columns for a given Hive table """
toReturn = {}
if not columns:
sql = 'SELECT * FROM %s LIMIT 0' %table
else:
sql = 'SELECT'
for c in columns:
sql += ' %s, ' % c
sql += 'FROM %s LIMIT 1' %table
result = runQueryDirectly(sql)
result.next()
toReturn['table'] = table
columns = []
num_of_columns = result.getMetaData().getColumnCount()
i = 1
while i <= num_of_columns:
column_to_add = {'index': i, 'label': result.getMetaData().getColumnLabel(i),
'type': result.getMetaData().getColumnType(i)}
columns.append(column_to_add)
i += 1
toReturn['columns'] = columns
return toReturn
def getTableDescription(table):
""" Returns a raw description of a Hive table"""
sql = 'DESCRIBE %s' % table
result = runQueryDirectly(sql)
return result
def getTableContents(table, columns=None, limit=None):
""" Generates a dictionary with full contents and descriptions for a given Hive table """
toReturn = {}
sql = getTableContentsSQL(table, columns, limit)
result = runQueryDirectly(sql)
toReturn['table'] = table
columns = []
num_of_columns = result.getMetaData().getColumnCount()
i = 1
while i <= num_of_columns:
column_to_add = {'index': i, 'label': result.getMetaData().getColumnLabel(i),
'type': result.getMetaData().getColumnType(i)}
columns.append(column_to_add)
i += 1
toReturn['columns'] = columns
rows = []
r = 0
while result.next():
r += 1
row_to_add = {}
for c in columns:
row_to_add[c['label']] = result.getString(c['index'])
rows.append(row_to_add)
toReturn['rows'] = rows
toReturn['row_count'] = r
toReturn['column_count'] = num_of_columns
return toReturn
def getTableContentsForDataTables(table, columns=None, limit=None):
""" Generates a JSON-formatted string with contents in a format supported for Datatables for a given Hive table.
See http://datatables.net/examples/data_sources/js_array.html for additional info
"""
toReturn = {}
sql = getTableContentsSQL(table, columns, limit)
result = runQueryDirectly(sql)
columns = []
num_of_columns = result.getMetaData().getColumnCount()
i = 1
while i <= num_of_columns:
column_to_add = {'sTitle': result.getMetaData().getColumnLabel(i)}
columns.append(column_to_add)
i += 1
toReturn['aoColumns'] = columns
rows = []
r = 0
while result.next():
r += 1
row_to_add = []
j = 1
while j <= num_of_columns:
row_to_add.append(result.getString(j))
j += 1
rows.append(row_to_add)
toReturn['aaData'] = rows
return json.dumps(toReturn)
def getTableContentsCSV(table, columns=None, limit=None):
""" Generates a CSV-formatted string with contents for a given Hive table. """
sql = getTableContentsSQL(table, columns, limit)
result = runQueryDirectly(sql)
string_thing = StringIO.StringIO()
csv_writer = csv.writer(string_thing)
num_of_columns = result.getMetaData().getColumnCount()
i = 1
columns = []
while i <= num_of_columns:
columns.append(result.getMetaData().getColumnLabel(i))
i += 1
csv_writer.writerow(columns)
while result.next():
row_to_add = []
j = 1
while j <= num_of_columns:
row_to_add.append(result.getString(j))
j += 1
csv_writer.writerow(row_to_add)
return string_thing.getvalue().strip('\r\n')
def getFunctionList():
""" Gets an array of functions from Hive. No details about the functions are returned. """
sql = "SHOW functions"
result = runQueryDirectly(sql)
functions = []
while result.next():
functions.append(result.getString(1))
return functions