Bulk insert using sea-query?

454 views Asked by At

How to construct a query with a bulk insert?

let (query, values) = Query::insert()
    .into_table(DbAppointmentService::Table)
    .columns([ 
        DbAppointmentService::Id,
        DbAppointmentService::AppointmentId,
        DbAppointmentService::Name,
        DbAppointmentService::Price,
        DbAppointmentService::Duration,
    ])
    .unexisting_bulk_insert_method(values) // What is the method to use to make a bulk insert?
    .build(PostgresQueryBuilder);
1

There are 1 answers

0
Roman Mahotskyi On BEST ANSWER

To make bulk insert in sea_query you can "split" builder declaration into multiple statements.

// Step 1: Create builder
let builder = Query::insert()
    .into_table(DbAppointmentService::Table)
    .columns([ 
        DbAppointmentService::Id,
        DbAppointmentService::AppointmentId,
        DbAppointmentService::Name,
        DbAppointmentService::Price,
        DbAppointmentService::Duration,
    ]).to_owned();

// Step 2: Execute `values_panic` on each loop step
for item of items.into_iter() { // where items is a vec of row's values
    builder.values_panic(vec![
        item.first.into(), 
        item.second.into(), 
        item.third.into()
    ]);
}

// Step 3: Build the query by using `build` method
let (query, values) = builder.build(PostgresQueryBuilder);

// Step 4: Use `query` and `values` as usual