-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
81 lines (66 loc) · 2 KB
/
main.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
import os
import psycopg2
from dotenv import load_dotenv
def get_variable_types(connection, table_name="users"):
"""Get column names and their types for the given table.
Implementative details:
- This query handles custom types and return their names."""
cursor = connection.cursor()
cursor.execute(
f"""SELECT
a.attname AS column_name,
format_type(a.atttypid, a.atttypmod) AS data_type
FROM
pg_attribute a
JOIN
pg_class c ON a.attrelid = c.oid
JOIN
pg_namespace n ON n.oid = c.relnamespace
WHERE
c.relname = '{table_name}'
AND n.nspname = 'public' -- or any other schema name
AND a.attnum > 0
ORDER BY
a.attnum;"""
)
variable_types = cursor.fetchall()
cursor.close()
return variable_types
def get_oid_of_Text(connection):
cursor = connection.cursor()
cursor.execute(
f"""SELECT * FROM pg_attribute
WHERE attrelid = (SELECT oid FROM pg_class WHERE relname = 'mytable');"""
)
variable_types = cursor.fetchall()
cursor.close()
return variable_types
def main():
load_dotenv()
try:
dbname = os.getenv("POSTGRES_DB")
user = os.getenv("POSTGRES_USER")
password = os.getenv("POSTGRES_PASSWORD")
port = os.getenv("PGPORT")
# Establishing a connection to the PostgreSQL database
conn = psycopg2.connect(
dbname=dbname,
user=user,
password=password,
host="localhost",
port=port,
)
# Get variable types
variable_types = get_variable_types(conn)
# Print the results
print("Variable Types:")
for column_name, data_type in variable_types:
print(f"{column_name}: {data_type}")
except psycopg2.Error as e:
print("Error connecting to the database:", e)
finally:
if conn is not None:
conn.close()
if __name__ == "__main__":
main()
get_oid_of_Text()