| 1 |
using Sqlite; |
| 2 |
|
| 3 |
namespace Qlite { |
| 4 |
|
| 5 |
public class InsertBuilder : StatementBuilder { |
| 6 |
|
| 7 |
// INSERT [OR ...] |
| 8 |
private bool replace_val; |
| 9 |
private string? or_val; |
| 10 |
|
| 11 |
// INTO [...] |
| 12 |
private Table table; |
| 13 |
private string table_name; |
| 14 |
|
| 15 |
// VALUES [...] |
| 16 |
private StatementBuilder.AbstractField[] fields = {}; |
| 17 |
|
| 18 |
internal InsertBuilder(Database db) { |
| 19 |
base(db); |
| 20 |
} |
| 21 |
|
| 22 |
public InsertBuilder replace() { |
| 23 |
this.replace_val = true; |
| 24 |
return this; |
| 25 |
} |
| 26 |
|
| 27 |
public InsertBuilder or(string or) { |
| 28 |
this.or_val = or; |
| 29 |
return this; |
| 30 |
} |
| 31 |
|
| 32 |
public InsertBuilder into(Table table) { |
| 33 |
this.table = table; |
| 34 |
this.table_name = table.name; |
| 35 |
return this; |
| 36 |
} |
| 37 |
|
| 38 |
public InsertBuilder into_name(string table) { |
| 39 |
this.table_name = table; |
| 40 |
return this; |
| 41 |
} |
| 42 |
|
| 43 |
public InsertBuilder value<T>(Column<T> column, T value) { |
| 44 |
fields += new Field<T>(column, value); |
| 45 |
return this; |
| 46 |
} |
| 47 |
|
| 48 |
public InsertBuilder value_null<T>(Column<T> column) { |
| 49 |
if (column.not_null) error("Qlite Error: ILLEGAL QUERY: Can't set non-null column %s to null", column.name); |
| 50 |
fields += new NullField<T>(column); |
| 51 |
return this; |
| 52 |
} |
| 53 |
|
| 54 |
internal override Statement prepare() { |
| 55 |
string fields_text = ""; |
| 56 |
string value_qs = ""; |
| 57 |
for (int i = 0; i < fields.length; i++) { |
| 58 |
if (i != 0) { |
| 59 |
value_qs += ", "; |
| 60 |
fields_text += ", "; |
| 61 |
} |
| 62 |
fields_text += ((!)fields[i].column).name; |
| 63 |
value_qs += "?"; |
| 64 |
} |
| 65 |
string sql = replace_val ? "REPLACE" : "INSERT"; |
| 66 |
if (!replace_val && or_val != null) sql += @" OR $((!)or_val)"; |
| 67 |
sql += @" INTO $table_name ( $fields_text ) VALUES ($value_qs)"; |
| 68 |
Statement stmt = db.prepare(sql); |
| 69 |
for (int i = 0; i < fields.length; i++) { |
| 70 |
fields[i].bind(stmt, i+1); |
| 71 |
} |
| 72 |
return stmt; |
| 73 |
} |
| 74 |
|
| 75 |
public int64 perform() { |
| 76 |
if (prepare().step() != DONE) { |
| 77 |
critical(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); |
| 78 |
} |
| 79 |
return db.last_insert_rowid(); |
| 80 |
} |
| 81 |
|
| 82 |
} |
| 83 |
|
| 84 |
} |