Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix pg init #4670

Merged
merged 1 commit into from
Oct 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions util/rich-indexer/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ impl SQLXPool {
pool
}
DBDriver::Postgres => {
self.postgres_init(db_config).await?;
let uri = build_url_for_postgres(db_config);
let connection_options =
AnyConnectOptions::from_str(&uri)?.log_statements(LevelFilter::Trace);
Expand All @@ -79,9 +80,6 @@ impl SQLXPool {
.set(pool.clone())
.map_err(|_| anyhow!("set pool failed"))?;

SQLXPool::new_query(r#"CREATE DATABASE IF NOT EXISTS "postgres""#)
.execute(&pool)
.await?;
self.create_tables_for_postgres().await?;

self.db_driver = DBDriver::Postgres;
Expand Down Expand Up @@ -207,6 +205,30 @@ impl SQLXPool {
}
Ok(())
}

pub async fn postgres_init(&mut self, db_config: &RichIndexerConfig) -> Result<()> {
// Connect to the "postgres" database first
let mut temp_config = db_config.clone();
temp_config.db_name = "postgres".to_string();
let uri = build_url_for_postgres(&temp_config);
let connection_options =
AnyConnectOptions::from_str(&uri)?.log_statements(LevelFilter::Trace);
let tmp_pool_options = AnyPoolOptions::new();
let pool = tmp_pool_options.connect_with(connection_options).await?;
// Check if database exists
let query =
SQLXPool::new_query(r#"SELECT EXISTS (SELECT FROM pg_database WHERE datname = $1)"#)
.bind(db_config.db_name.as_str());
let row = query.fetch_one(&pool).await?;
// If database does not exist, create it
if !row.get::<bool, _>(0) {
let query = format!(r#"CREATE DATABASE "{}""#, db_config.db_name);
SQLXPool::new_query(&query).execute(&pool).await?;
Ok(())
} else {
Ok(())
}
}
}

fn build_url_for_sqlite(db_config: &RichIndexerConfig) -> String {
Expand Down
Loading