1 module appbase.mysql.dao;
2 
3 import database.mysql;
4 
5 alias DataRow = string[string];
6 alias DataRows = DataRow[];
7 
8 DataRow queryOneRow(bool Prepared = true, Params...)(Connection conn, string cmd, Params params)
9 {
10     DataRows rows = query!(Prepared)(conn, cmd, params);
11 
12     if (rows.length == 0)
13     {
14         return null;
15     }
16 
17     return rows[0];
18 }
19 
20 DataRows query(bool Prepared = true, Params...)(Connection conn, string cmd, Params params)
21 {
22     DataRows rows;
23     
24     static if (Prepared)
25         conn.execute(cmd, params, (MySQLRow row) {
26             rows ~= row.toAA();
27         });
28     else
29         conn.executeNoPrepare(cmd, params, (MySQLRow row) {
30             rows ~= row.toAA();
31         });
32 
33     return rows;
34 }
35 
36 // Return affected, no lastInsertId.
37 // Get the lastInsertId: use conn.lastInsertId() please.
38 ulong exec(bool Prepared = true, Params...)(Connection conn, string cmd, Params params)
39 {
40     static if (Prepared)
41     {
42         auto upd = conn.prepare(cmd);
43         conn.execute(upd, params);
44     }
45     else
46     {
47         conn.executeNoPrepare(cmd, params);
48     }
49 
50     return conn.affected();
51 }
52 
53 DataRows selectDataRows(DataRows rows, string key, string value)
54 {
55     int start = -1;
56     int end = -1;
57 
58     int i = 0;
59     while (i < rows.length)
60     {
61         if (rows[i][key] == value)
62         {
63             start = i;
64             break;
65         }
66 
67         i++;
68     }
69 
70     if (start < 0)
71     {
72         return rows[0 .. 0];
73     }
74 
75     i = start + 1;
76     while (i < rows.length)
77     {
78         if (rows[i][key] != value)
79         {
80             end = i;
81             break;
82         }
83 
84         i++;
85     }
86 
87     if (end < 0)
88     {
89         end = cast(int)rows.length;
90     }
91 
92     return rows[start .. end];
93 }
94 
95 DataRows selectDataRows(DataRows rows, int rowsInPage, int pageno)
96 {
97     if (rows.length == 0) return rows;
98     if ((pageno - 1) * rowsInPage > cast(int)rows.length - 1) return rows[0 .. 0];
99     return rows[(pageno - 1) * rowsInPage .. (pageno * rowsInPage >= rows.length) ? rows.length : pageno * rowsInPage];
100 }