· 8 years ago · Feb 20, 2018, 08:46 PM
1import sqlite3
2import re
3
4insert = """
5INSERT INTO tools (pocket, tool, description, X, Y, Z, A, B, C, U, V, W, D, orientation, frontangle, backangle)
6VALUES (:Pocket, :Tool, ":Comment", :X, :Y, :Z, :A, :B, :C, :U, :V, :W, :Diameter, :Orientation, :Frontangle, :Backangle);
7"""
8
9schema = """
10BEGIN TRANSACTION;
11DROP TABLE IF EXISTS tools;
12CREATE TABLE tools (
13 tool INTEGER PRIMARY KEY UNIQUE NOT NULL,
14 pocket INTEGER NOT NULL,
15 description TEXT DEFAULT "",
16 X REAL DEFAULT 0.0,
17 Y REAL DEFAULT 0.0,
18 Z REAL DEFAULT 0.0,
19 A REAL DEFAULT 0.0,
20 B REAL DEFAULT 0.0,
21 C REAL DEFAULT 0.0,
22 U REAL DEFAULT 0.0,
23 V REAL DEFAULT 0.0,
24 W REAL DEFAULT 0.0,
25 D REAL DEFAULT 0.0,
26 orientation INTEGER DEFAULT NULL,
27 frontangle REAL DEFAULT NULL,
28 backangle REAL DEFAULT NULL
29);
30COMMIT;
31"""
32
33def dict_into_query(q, d):
34 "replaces each occurence of :key in the input file with the textual representation of the value of d[key]"
35
36 f = re.search(':([\w]+)', q)
37 while f:
38 if f.group(1) in d:
39 if d[f.group(1)]:
40 q = q[:f.start()] + str(d[f.group(1)]) + q[f.end():]
41 else:
42 q = q[:f.start()] + "NULL" + q[f.end():]
43 else: #Tags that are in the query, but not the dict
44 q = q[:f.start()] + "NULL" + q[f.end():]
45 f = re.search(':([\w]+)', q)
46 return q
47
48
49db = sqlite3.connect('tools.db')
50db.executescript(schema)
51
52tbl = open("sim.tbl")
53for t in tbl.readlines():
54 tool = {'Tool':re.search('[Tt]([0-9+-.]+) ', t),
55 'Pocket':re.search('[Pp]([0-9+-.]+)', t),
56 'X':re.search('[Xx]([0-9+-.]+)', t),
57 'Y':re.search('[Yy]([0-9+-.]+)', t),
58 'Z':re.search('[Zz]([0-9+-.]+)', t),
59 'A':re.search('[Aa]([0-9+-.]+)', t),
60 'B':re.search('[Bb]([0-9+-.]+)', t),
61 'C':re.search('[Cc]([0-9+-.]+)', t),
62 'U':re.search('[Uu]([0-9+-.]+)', t),
63 'V':re.search('[Vv]([0-9+-.]+)', t),
64 'W':re.search('[Ww]([0-9+-.]+)', t),
65 'Diameter':re.search('[Dd]([0-9+-.]+)', t),
66 'Frontangle':re.search('[Ii]([0-9+-.]+)', t),
67 'Backangle':re.search('[Jj]([0-9+-.]+)', t),
68 'Orientation':re.search('[Qq]([0-9+-.]+)', t),
69 'Comment':re.search(';(.*)', t)}
70 for m in tool:
71 if tool[m]:
72 tool[m] = tool[m].group(1)
73 db.executescript(dict_into_query(insert, tool))