/// Initialize the database when the table doesn't exist already
InitDatabase {
+ #[arg(long)]
+ dbname: String,
+
#[arg(long)]
host: String,
}
match args.action {
- Action::InitDatabase{ host, user, password } => {
- println!("initializing the database with user {}", user);
- let _client = postgres::Config::new()
+ Action::InitDatabase{ dbname, host, user, password } => {
+ println!("maybe creating the database");
+ let mut client = postgres::Config::new()
.dbname("postgres")
.host(&host.to_string())
.user(&user.to_string())
+ .password(password.clone())
+ .connect(NoTls)?;
+
+ let result =
+ client.query("SELECT 1 FROM pg_database WHERE datname=$1",&[&dbname])?;
+
+ if result.is_empty() {
+ println!("creating database {}", dbname);
+ client.execute(&format!("create database {}",dbname),&[])?;
+ } else {
+ println!("database {} exists already", dbname);
+ }
+ let _ = client.close();
+
+ println!("maybe creating database objects");
+ let mut client = postgres::Config::new()
+ .dbname(&dbname)
+ .host(&host.to_string())
+ .user(&user.to_string())
.password(password)
.connect(NoTls)?;
+
+ client.execute("CREATE EXTENSION IF NOT EXISTS vector", &[])?;
+ client.execute(
+ "CREATE TABLE if not exists documents \
+ (id serial PRIMARY KEY, content text, \
+ embedding vector(384))", &[])?;
+
}
_ => {}
}