-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsetup_postgresql.py
More file actions
135 lines (112 loc) Β· 4.35 KB
/
Copy pathsetup_postgresql.py
File metadata and controls
135 lines (112 loc) Β· 4.35 KB
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
#!/usr/bin/env python3
# StartWithA
# Copyright (C) 2024-2026 Kiran Mathews
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
PostgreSQL setup script - tries different authentication methods
"""
import os
import subprocess
import psycopg2
def try_create_database():
"""Try different methods to create the PostgreSQL database"""
print("π Attempting to create PostgreSQL database...")
# Method 1: Try with system postgres user
try:
print("π Method 1: Using system postgres user...")
result = subprocess.run([
'sudo', '-u', 'postgres', 'psql', '-c',
"CREATE DATABASE investment_checklist;"
], capture_output=True, text=True)
if result.returncode == 0:
print("β
Database created successfully!")
return True
else:
print(f"β Failed: {result.stderr}")
except Exception as e:
print(f"β Method 1 failed: {e}")
# Method 2: Try with peer authentication
try:
print("π Method 2: Using peer authentication...")
conn = psycopg2.connect(
host="localhost",
database="postgres",
user=os.getenv("USER", "postgres")
)
conn.autocommit = True
cursor = conn.cursor()
# Check if database exists
cursor.execute("SELECT 1 FROM pg_database WHERE datname='investment_checklist'")
if not cursor.fetchone():
cursor.execute("CREATE DATABASE investment_checklist")
print("β
Database created successfully!")
else:
print("βΉοΈ Database already exists!")
cursor.close()
conn.close()
return True
except Exception as e:
print(f"β Method 2 failed: {e}")
# Method 3: Manual instructions
print("\nπ Manual Setup Required:")
print("Please run these commands manually:")
print("1. sudo -u postgres psql")
print("2. CREATE DATABASE investment_checklist;")
print("3. \\q")
print("\nOr configure PostgreSQL authentication for your user.")
return False
def test_connection():
"""Test connection to the investment_checklist database"""
connection_strings = [
f"postgresql://{os.getenv('USER', 'postgres')}@localhost/investment_checklist",
"postgresql://postgres@localhost/investment_checklist",
"postgresql://localhost/investment_checklist",
]
print("\nπ Testing database connections...")
for conn_str in connection_strings:
try:
print(f"Testing: {conn_str}")
conn = psycopg2.connect(conn_str)
conn.close()
print(f"β
Connection successful!")
# Update .env file
with open('.env', 'r') as f:
content = f.read()
content = content.replace(
"DATABASE_URL='postgresql://localhost/investment_checklist'",
f"DATABASE_URL='{conn_str}'"
)
with open('.env', 'w') as f:
f.write(content)
print(f"β
Updated .env with working connection string")
return True
except Exception as e:
print(f"β Failed: {e}")
return False
if __name__ == "__main__":
print("π PostgreSQL Setup Script")
print("=" * 40)
# Try to create database
if try_create_database():
# Test connection
if test_connection():
print("\nπ PostgreSQL setup complete!")
print("β
Database created and connection tested")
print("π You can now run: flask db upgrade")
else:
print("\nβ οΈ Database created but connection issues")
else:
print("\nβ Could not create database automatically")
print("Please create it manually and update DATABASE_URL in .env")