pythonpostgresqlgoogle-cloud-platformsqlalchemyunix-socket

Connecting to PostgreSQL on Google Cloud Platform using Unix Sockets and SQLAlchemy


I am trying to connect to a PostgreSQL database hosted on a Google Cloud Platform instance using unix sockets and the SQLAlchemy library. My database instance is configured to accept unix socket connections.

When I run my application locally, I use the following line to connect to the database and it works perfectly:

pool = create_engine("postgresql://{user}:{password}@/{dbname}?host={socket}".format(params_dic))

However, when I run the same application on Google Cloud Platform, I get an error with the following connection string:

pool = create_engine(engine.url.URL.create(
    drivername="postgresql+psycopg2",
    username=params_dic['user'],
    password=params_dic['password'],
    database=params_dic['dbname'], 
    query={"unix_socket": "{}/.s.PGSQL.5432".format(params_dic['socket'])},
    ),
pool_size=5,
max_overflow=2,
pool_timeout=30,
pool_recycle=100,)

The error message is: (psycopg2.ProgrammingError) invalid dsn: invalid connection option "unix_socket"

How can I connect to a PostgreSQL database on Google Cloud Platform using unix sockets and SQLAlchemy?

I Tried connecting to GCP Postgres with unix socket and SQLAlchemy, expected success but got error "invalid dsn: invalid connection option "unix_socket"

Also I dont want to use a Public IP conection.


Solution

  • I was able to solve it using the psycopg2 library directly, there was also a missing line in the .yaml file to add the instance to the uinx socket. Thank you all.

    de function:

    def connect(params_dic):
        """ 
        Generate the connection to the database
        """
        if is_gcp():
            print('coneccting from GCP...')
            conn = None
            try:
                conn = ppg2.connect(
                    host=params_dic['socket_dir']+'/'+params_dic['socket'],
                    database = params_dic['dbname'],
                    user = params_dic['user'],
                    password = params_dic['password'],
                    )
                return conn
            except Exception as error:
                print('problema en la funcion ppg2: ',error)
        else:
            print("Running locally")
            conn = None
            try:
                # connect to the PostgreSQL server
                conn = ppg2.connect(**params_dic)
            except (Exception, ppg2.DatabaseError) as error:
                print(error)
            return conn
    

    the missing line in the yaml file

    beta_settings:
        cloud_sql_instances: proyect-name:region:instance-name