aboutsummaryrefslogtreecommitdiff
path: root/qlite/src/delete_builder.vala
blob: 5999dc408e1a3173cea6ec22ecb7a4bf71ab2da3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using Sqlite;

namespace Qlite {

public class DeleteBuilder : StatementBuilder {

    // DELETE FROM [...]
    private Table table;
    private string table_name;

    // WHERE [...]
    private string selection;
    private StatementBuilder.Field[] selection_args;

    protected DeleteBuilder(Database db) {
        base(db);
    }

    public DeleteBuilder from(Table table) {
        if (table != null) throw new DatabaseError.ILLEGAL_QUERY("cannot use from() multiple times.");
        this.table = table;
        this.table_name = table.name;
        return this;
    }

    public DeleteBuilder from_name(string table) {
        this.table_name = table;
        return this;
    }

    public DeleteBuilder where(string selection, string[]? selection_args = null) {
        if (selection != null) throw new DatabaseError.ILLEGAL_QUERY("selection was already done, but where() was called.");
        this.selection = selection;
        if (selection_args != null) {
            this.selection_args = new StatementBuilder.Field[selection_args.length];
            for (int i = 0; i < selection_args.length; i++) {
                this.selection_args[i] = new StatementBuilder.StringField(selection_args[i]);
            }
        }
        return this;
    }

    public DeleteBuilder with<T>(Column<T> column, string comp, T value) {
        if (selection == null) {
            selection = @"$(column.name) $comp ?";
            selection_args = { new StatementBuilder.Field<T>(column, value) };
        } else {
            selection = @"($selection) AND $(column.name) $comp ?";
            StatementBuilder.Field[] selection_args_new = new StatementBuilder.Field[selection_args.length+1];
            for (int i = 0; i < selection_args.length; i++) {
                selection_args_new[i] = selection_args[i];
            }
            selection_args_new[selection_args.length] = new Field<T>(column, value);
            selection_args = selection_args_new;
        }
        return this;
    }

    public override Statement prepare() {
        Statement stmt = db.prepare(@"DELETE FROM $table_name $(selection != null ? @"WHERE $selection": "")");
        for (int i = 0; i < selection_args.length; i++) {
            selection_args[i].bind(stmt, i+1);
        }
        return stmt;
    }

    public void perform() {
        if (prepare().step() != DONE) {
            throw new DatabaseError.EXEC_ERROR(@"SQLite error: $(db.errcode()) - $(db.errmsg())");
        }
    }

}

}