· 8 years ago · Mar 24, 2018, 10:06 PM
1static func insert( product : [String:Any] ) -> Bool {
2 print("nInsert: (product["display_name"]!)n")
3
4 // PREPARA A QUERY
5 var auxStr: String = "INSERT INTO product ("
6 var auxValues: String = " VALUES ("
7
8 for s in fieldsProducts {
9 if fieldsProducts.last == s {
10 auxStr += s + ")"
11 auxValues += "?);"
12 } else {
13 auxStr += s + ","
14 auxValues += "?,"
15 }
16 }
17
18 //print("Query: (auxStr) n Values: (auxValues)")
19 let insertQuery = auxStr + auxValues
20 print("Query: (insertQuery)")
21 // FIM PREPARA A QUERY
22
23 var stmt: OpaquePointer? = nil
24
25 if sqlite3_open(fileUrl.path, &db) != SQLITE_OK {
26 print("Error openning database")
27 return false
28 }
29
30 if sqlite3_prepare(db,insertQuery,-1,&stmt,nil) != SQLITE_OK {
31 print("Error to binding a query")
32 return false
33 }
34
35 var count : Int32 = 1
36
37 for (key,value) in product {
38 print(count)
39 if value is String {
40 print("(key) String: (value)")
41 sqlite3_bind_text(db, count, String(describing: value), -1, nil)
42 } else if value is Int {
43 print("(key) Int: (value)")
44 sqlite3_bind_int(db, count, Int32(value as! Int))
45 } else if value is Float {
46 print("(key) Float: (value)")
47 sqlite3_bind_double(db, count, Double(value as! Double))
48 } else if value is [Int] {
49 print("(key) [Int]: (value)")
50 let idsList = value as! [Int]
51 var str: String = ""
52
53 for j in idsList {
54 if idsList.last == j {
55 str += String(j)
56 } else {
57 str += String(j) + ","
58 }
59 }
60 print("Item list: (str)")
61 sqlite3_bind_text(db, count, str, -1, nil)
62 } else if value is Bool {
63 print("(key) Bool: (value)")
64 var num : Int32 = 0
65 if Bool(value as! Bool) {
66 num = 1
67 } else {
68 num = 0
69 }
70 sqlite3_bind_int(db,count,num)
71 }
72
73 count += 1
74 }
75
76 if sqlite3_step(stmt) == SQLITE_DONE {
77 print("Save successfuly: (product["display_name"]!)")
78 return true
79 }
80
81 return false
82 }
83
84static func create() {
85
86 if sqlite3_open(fileUrl.path, &db) != SQLITE_OK {
87 print("Error openning database")
88 return
89 }
90
91 let createTableQuery = "CREATE TABLE IF NOT EXISTS product(id integer primary key," +
92 "name text," +
93 "default_code text," +
94 "destination_type text," +
95 "company_ax_id integer," +
96 "categ_id integer," +
97 "fiscal_class_code text," +
98 "taxes_id text," +
99 "uom_id integer," +
100 "uom_po_id integer," +
101 "multiple integer, " +
102 "__last_update text, " +
103 "display_name text, " +
104 "active boolean, " +
105 "create_date text, " +
106 "create_uid integer, " +
107 "currency_id integer," +
108 "invoice_police text, " +
109 "item_ids text," +
110 "list_price text, " +
111 "price float," +
112 "pricelist_id integer, " +
113 "type text);"
114
115 if sqlite3_exec(db,createTableQuery,nil,nil,nil) != SQLITE_OK {
116 print("Erro ao criar tabela!")
117 return
118 }
119
120 print("ProductDB: Banco carregado e tabela pronta!")
121}