1

I'm currently trying to create a postgresql database using sqlalchemy and would like this database file to be created in an external hard drive. I can do that using sqlite3 which can be done just be adding the path after the string that will go into the engine:

# To create the tables we need these packages
import sqlalchemy as sql
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy import create_engine 

# Creating the base.
Base = declarative_base()

# The tables would be defined here.

# Create an engine that stores data in the given directory.
path = '/path/'
engine = create_engine('sqlite:///'+path+'ARsdb.db')    

# Create all tables in the engine.
Base.metadata.create_all(engine)

Which will then make the database file within the specified path. On the other hand postgresql uses a different syntax for the engine:

# default
engine = create_engine('postgresql://user:pass@localhost/mydatabase')

# psycopg2
engine = create_engine('postgresql+psycopg2://user:pass@localhost/mydatabase')

as explained on this question or the documentation. However it is not clear for me if I can specify a path for this database file to be written like on the sqlite. When I created the database using the database string as:

postgresql://user:password@localhost:5432/databasepath/database_name

for a mock database I couldn't find the database_name file inside the databasepath path. Can I specify a path for the file to be created after all or they stay confined within the server created during postgresql installation?

Thanks!

Chicrala
  • 994
  • 12
  • 23

1 Answers1

2

No, that's not possible.

Postgres stores the data for all databases of a cluster (aka "instance") inside a single directory which is specified during the creation of the Postgres instance (via initdb).

Additionally, you can't create a database by connecting to it. You need to first run the create database command, only then you can connect to it.