Sqlx create table from file creating own migration function

I am creating my own migrations function due to too much issue with sqlx built-in migration.
The problem I am facing is, its not creating the tables.
Please help. Thanks.

Code below

db_migration.rs

use futures::future::join_all;
use sqlx::{query, PgPool};
use tokio::fs;
use tracing::warn;

pub async fn db_migrate(db: &PgPool) {
    let p: &str = "db/migrations";

    let mut list = if let Ok(x) = fs::read_dir(p).await {
        x
    } else {
        warn!("Read directory fail");
        return;
    };

    let mut files: Vec<String> = Vec::new();

    while let Ok(Some(x)) = list.next_entry().await {
        let f: String = x.file_name().into_string().unwrap_or_default();

        if f.len() > 0 {
            files.push(format!("{}/{}", p, f));
        }
    }

    join_all(files.iter().map(|x| query(x).execute(db))).await;
}

This is what I am getting PgError.

Err(Database(PgDatabaseError { severity: Error, code: "42601", message: "syntax error at or near \"db\"", detail: None, hint: None, position: Some(Original(1)), where: None, schema: None, table: None, column: None, data_type: None, constraint: None, file: Some("scan.l"), line: Some(1244), routine: Some("scanner_yyerror") }))

Looks to me like your scan.l file is broken.

But there is no scan.l file exists.

You're using the files' names as queries instead of the files' content. Also I'm not sure, but migrations should probably be kept well ordered and sequential. You probably don't want to start executing a migration before the previous one had time to finish and commit its transactions.

You should troubleshoot your issues with sqlx migrate functions and use that instead.

1 Like