# Install PostgreSQL using official repositorysudoaptupdate
sudoaptinstall-ypostgresql-16postgresql-client-16postgresql-contrib-16
# Or using Homebrew on macOSbrewinstallpostgresql@16
# Or using Docker for developmentdockerrun--namepostgres-dev\-ePOSTGRES_PASSWORD=devpassword\-ePOSTGRES_DB=development\-p5432:5432\-dpostgres:16
# Using pg_versions for multiple PostgreSQL versionscurl-sSLhttps://raw.githubusercontent.com/markw/pg_versions/master/install.sh|bash
# Install multiple versionspg_versionsinstall14pg_versionsinstall15pg_versionsinstall16# Switch between versionspg_versionsuse16
-- Connect to your development database\cdevelopment-- Essential extensions for developmentCREATEEXTENSIONIFNOTEXISTS"uuid-ossp";CREATEEXTENSIONIFNOTEXISTS"pgcrypto";CREATEEXTENSIONIFNOTEXISTS"pg_stat_statements";CREATEEXTENSIONIFNOTEXISTS"btree_gin";CREATEEXTENSIONIFNOTEXISTS"btree_gist";CREATEEXTENSIONIFNOTEXISTS"hstore";CREATEEXTENSIONIFNOTEXISTS"ltree";CREATEEXTENSIONIFNOTEXISTS"unaccent";-- For geospatial developmentCREATEEXTENSIONIFNOTEXISTS"postgis";CREATEEXTENSIONIFNOTEXISTS"postgis_topology";CREATEEXTENSIONIFNOTEXISTS"fuzzystrmatch";CREATEEXTENSIONIFNOTEXISTS"postgis_tiger_geocoder";-- For full-text searchCREATEEXTENSIONIFNOTEXISTS"pg_trgm";-- For JSON operationsCREATEEXTENSIONIFNOTEXISTS"jsquery";-- For time series (if needed)CREATEEXTENSIONIFNOTEXISTS"timescaledb";
-- Create development databasesCREATEDATABASEdevelopment;CREATEDATABASEtesting;CREATEDATABASEstaging;-- Create development user with appropriate privilegesCREATEUSERdev_userWITHPASSWORD'dev_password';GRANTALLPRIVILEGESONDATABASEdevelopmentTOdev_user;GRANTALLPRIVILEGESONDATABASEtestingTOdev_user;GRANTALLPRIVILEGESONDATABASEstagingTOdev_user;-- Grant schema privileges\cdevelopmentGRANTALLONSCHEMApublicTOdev_user;GRANTALLPRIVILEGESONALLTABLESINSCHEMApublicTOdev_user;GRANTALLPRIVILEGESONALLSEQUENCESINSCHEMApublicTOdev_user;GRANTALLPRIVILEGESONALLFUNCTIONSINSCHEMApublicTOdev_user;-- Set default privileges for future objectsALTERDEFAULTPRIVILEGESINSCHEMApublicGRANTALLONTABLESTOdev_user;ALTERDEFAULTPRIVILEGESINSCHEMApublicGRANTALLONSEQUENCESTOdev_user;ALTERDEFAULTPRIVILEGESINSCHEMApublicGRANTALLONFUNCTIONSTOdev_user;
#!/bin/bash# scripts/dev-setup.sh# Create development environmentecho"Setting up PostgreSQL development environment..."# Create databasespsql-Upostgres-c"CREATE DATABASE IF NOT EXISTS development;"psql-Upostgres-c"CREATE DATABASE IF NOT EXISTS testing;"# Create userpsql-Upostgres-c"CREATE USER IF NOT EXISTS dev_user WITH PASSWORD 'dev_password';"psql-Upostgres-c"GRANT ALL PRIVILEGES ON DATABASE development TO dev_user;"psql-Upostgres-c"GRANT ALL PRIVILEGES ON DATABASE testing TO dev_user;"# Install extensionspsql-Udev_user-ddevelopment-c"CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";"psql-Udev_user-ddevelopment-c"CREATE EXTENSION IF NOT EXISTS \"pgcrypto\";"psql-Udev_user-ddevelopment-c"CREATE EXTENSION IF NOT EXISTS \"pg_stat_statements\";"echo"Development environment setup complete!"
-- Create test database with isolated schemaCREATEDATABASEtesting;-- Connect to test database\ctesting-- Create test schemaCREATESCHEMAtest_schema;-- Create test userCREATEUSERtest_userWITHPASSWORD'test_password';GRANTALLPRIVILEGESONDATABASEtestingTOtest_user;GRANTALLPRIVILEGESONSCHEMAtest_schemaTOtest_user;-- Set up test dataCREATETABLEtest_schema.users(idSERIALPRIMARYKEY,usernameVARCHAR(50)UNIQUENOTNULL,emailVARCHAR(100)UNIQUENOTNULL,created_atTIMESTAMPDEFAULTCURRENT_TIMESTAMP);-- Insert test dataINSERTINTOtest_schema.users(username,email)VALUES('testuser1','test1@example.com'),('testuser2','test2@example.com'),('testuser3','test3@example.com');
# tests/conftest.pyimportpytestimportpsycopg2frompsycopg2.extensionsimportISOLATION_LEVEL_AUTOCOMMIT@pytest.fixture(scope="session")deftest_db():"""Create test database for the session."""conn=psycopg2.connect(host="localhost",database="postgres",user="postgres",password="postgres")conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)withconn.cursor()ascur:cur.execute("DROP DATABASE IF EXISTS test_db;")cur.execute("CREATE DATABASE test_db;")conn.close()# Return connection to test databasetest_conn=psycopg2.connect(host="localhost",database="test_db",user="postgres",password="postgres")yieldtest_conntest_conn.close()# Cleanupcleanup_conn=psycopg2.connect(host="localhost",database="postgres",user="postgres",password="postgres")cleanup_conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)withcleanup_conn.cursor()ascur:cur.execute("DROP DATABASE test_db;")cleanup_conn.close()@pytest.fixturedeftest_table(test_db):"""Create test table for each test."""withtest_db.cursor()ascur:cur.execute(""" CREATE TABLE IF NOT EXISTS test_table ( id SERIAL PRIMARY KEY, name VARCHAR(100), value INTEGER ); """)test_db.commit()yieldtest_db# Cleanup after each testwithtest_db.cursor()ascur:cur.execute("DROP TABLE IF EXISTS test_table;")test_db.commit()
# monitoring/dev_monitor.pyimportpsycopg2importtimeimportjsonfromdatetimeimportdatetimeclassPostgreSQLMonitor:def__init__(self,connection_params):self.conn_params=connection_paramsself.conn=Nonedefconnect(self):"""Connect to PostgreSQL."""self.conn=psycopg2.connect(**self.conn_params)defget_connection_stats(self):"""Get connection statistics."""withself.conn.cursor()ascur:cur.execute(""" SELECT count(*) as total_connections, count(*) FILTER (WHERE state = 'active') as active_connections, count(*) FILTER (WHERE state = 'idle') as idle_connections FROM pg_stat_activity; """)returncur.fetchone()defget_database_size(self):"""Get database size."""withself.conn.cursor()ascur:cur.execute(""" SELECT pg_size_pretty(pg_database_size(current_database())); """)returncur.fetchone()[0]defget_table_sizes(self):"""Get table sizes."""withself.conn.cursor()ascur:cur.execute(""" SELECT schemaname, tablename, pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) as size FROM pg_tables WHERE schemaname = 'public' ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC; """)returncur.fetchall()defmonitor_loop(self,interval=60):"""Run monitoring loop."""whileTrue:try:stats={'timestamp':datetime.now().isoformat(),'connections':self.get_connection_stats(),'database_size':self.get_database_size(),'table_sizes':self.get_table_sizes()}print(json.dumps(stats,indent=2))time.sleep(interval)exceptExceptionase:print(f"Monitoring error: {e}")time.sleep(interval)# Usageif__name__=="__main__":monitor=PostgreSQLMonitor({'host':'localhost','database':'development','user':'dev_user','password':'dev_password'})monitor.connect()monitor.monitor_loop(interval=30)
# 1. Install PostgreSQLsudoaptinstallpostgresql-16postgresql-client-16postgresql-contrib-16
# 2. Create development databasespsql-Upostgres-c"CREATE DATABASE development;"psql-Upostgres-c"CREATE DATABASE testing;"# 3. Create development userpsql-Upostgres-c"CREATE USER dev_user WITH PASSWORD 'dev_password';"psql-Upostgres-c"GRANT ALL PRIVILEGES ON DATABASE development TO dev_user;"# 4. Install extensionspsql-Udev_user-ddevelopment-c"CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";"psql-Udev_user-ddevelopment-c"CREATE EXTENSION IF NOT EXISTS \"pgcrypto\";"