anotherim-desktop/qlite/src/upsert_builder.vala

90 lines
2.7 KiB
Vala
Raw Normal View History

2017-08-25 22:05:36 +00:00
using Sqlite;
namespace Qlite {
public class UpsertBuilder : StatementBuilder {
// INTO [...]
private Table table;
private string table_name;
// VALUES [...]
private StatementBuilder.AbstractField[] keys = {};
private StatementBuilder.AbstractField[] fields = {};
internal UpsertBuilder(Database db, Table table) {
base(db);
this.table = table;
this.table_name = table.name;
}
public UpsertBuilder value<T>(Column<T> column, T value, bool key = false) {
if (key) {
keys += new Field<T>(column, value);
} else {
fields += new Field<T>(column, value);
}
return this;
}
2017-10-28 21:48:07 +00:00
public UpsertBuilder value_null<T>(Column<T> column) {
if (column.not_null) error("Can't set non-null column %s to null", column.name);
2017-08-25 22:05:36 +00:00
fields += new NullField<T>(column);
return this;
}
2017-10-28 21:48:07 +00:00
internal override Statement prepare() {
error("prepare() not available for upsert.");
2017-08-25 22:05:36 +00:00
}
2020-06-10 21:40:00 +00:00
internal Statement prepare_upsert() {
var unique_fields = new StringBuilder();
var unique_values = new StringBuilder();
var update_fields = new StringBuilder();
var update_values = new StringBuilder();
var update_fields_vals = new StringBuilder();
2017-08-25 22:05:36 +00:00
for (int i = 0; i < keys.length; i++) {
if (i != 0) {
2020-06-10 21:40:00 +00:00
unique_fields.append(", ");
unique_values.append(", ");
2017-08-25 22:05:36 +00:00
}
2020-06-10 21:40:00 +00:00
unique_fields.append(keys[i].column.name);
unique_values.append("?");
2017-08-25 22:05:36 +00:00
}
for (int i = 0; i < fields.length; i++) {
if (i != 0) {
2020-06-10 21:40:00 +00:00
update_fields.append(", ");
update_values.append(", ");
update_fields_vals.append(", ");
2017-08-25 22:05:36 +00:00
}
2020-06-10 21:40:00 +00:00
update_fields.append(fields[i].column.name);
update_values.append("?");
update_fields_vals.append(fields[i].column.name).append("=excluded.").append(fields[i].column.name);
2017-08-25 22:05:36 +00:00
}
2020-06-10 21:40:00 +00:00
string sql = @"INSERT INTO $table_name ($(unique_fields.str), $(update_fields.str)) VALUES ($(unique_values.str), $(update_values.str)) " +
@"ON CONFLICT ($(unique_fields.str)) DO UPDATE SET $(update_fields_vals.str)";
2017-08-25 22:05:36 +00:00
Statement stmt = db.prepare(sql);
for (int i = 0; i < keys.length; i++) {
2020-06-10 21:40:00 +00:00
keys[i].bind(stmt, i + 1);
}
for (int i = 0; i < fields.length; i++) {
fields[i].bind(stmt, i + keys.length + 1);
2017-08-25 22:05:36 +00:00
}
return stmt;
}
2017-10-28 21:48:07 +00:00
public int64 perform() {
2020-06-10 21:40:00 +00:00
if (prepare_upsert().step() != DONE) {
critical(@"SQLite error: %d - %s", db.errcode(), db.errmsg());
2017-08-25 22:05:36 +00:00
}
return db.last_insert_rowid();
}
}
2017-10-28 21:48:07 +00:00
}