Coverage for ase/db/sqlite.py: 88.95%

552 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1"""SQLite3 backend. 

2 

3Versions: 

4 

51) Added 3 more columns. 

62) Changed "user" to "username". 

73) Now adding keys to keyword table and added an "information" table containing 

8 a version number. 

94) Got rid of keywords. 

105) Add fmax, smax, mass, volume, charge 

116) Use REAL for magmom and drop possibility for non-collinear spin 

127) Volume can be None 

138) Added name='metadata' row to "information" table 

149) Row data is now stored in binary format. 

15""" 

16 

17import json 

18import numbers 

19import os 

20import sqlite3 

21import sys 

22from contextlib import contextmanager 

23 

24import numpy as np 

25 

26import ase.io.jsonio 

27from ase.calculators.calculator import all_properties 

28from ase.data import atomic_numbers 

29from ase.db.core import ( 

30 Database, 

31 bytes_to_object, 

32 invop, 

33 lock, 

34 now, 

35 object_to_bytes, 

36 ops, 

37 parse_selection, 

38) 

39from ase.db.row import AtomsRow 

40from ase.parallel import parallel_function 

41 

42VERSION = 9 

43 

44init_statements = [ 

45 """CREATE TABLE systems ( 

46 id INTEGER PRIMARY KEY AUTOINCREMENT, -- ID's, timestamps and user name 

47 unique_id TEXT UNIQUE, 

48 ctime REAL, 

49 mtime REAL, 

50 username TEXT, 

51 numbers BLOB, -- stuff that defines an Atoms object 

52 positions BLOB, 

53 cell BLOB, 

54 pbc INTEGER, 

55 initial_magmoms BLOB, 

56 initial_charges BLOB, 

57 masses BLOB, 

58 tags BLOB, 

59 momenta BLOB, 

60 constraints TEXT, -- constraints and calculator 

61 calculator TEXT, 

62 calculator_parameters TEXT, 

63 energy REAL, -- calculated properties 

64 free_energy REAL, 

65 forces BLOB, 

66 stress BLOB, 

67 dipole BLOB, 

68 magmoms BLOB, 

69 magmom REAL, 

70 charges BLOB, 

71 key_value_pairs TEXT, -- key-value pairs and data as json 

72 data BLOB, 

73 natoms INTEGER, -- stuff for making queries faster 

74 fmax REAL, 

75 smax REAL, 

76 volume REAL, 

77 mass REAL, 

78 charge REAL)""", 

79 """CREATE TABLE species ( 

80 Z INTEGER, 

81 n INTEGER, 

82 id INTEGER, 

83 FOREIGN KEY (id) REFERENCES systems(id))""", 

84 """CREATE TABLE keys ( 

85 key TEXT, 

86 id INTEGER, 

87 FOREIGN KEY (id) REFERENCES systems(id))""", 

88 """CREATE TABLE text_key_values ( 

89 key TEXT, 

90 value TEXT, 

91 id INTEGER, 

92 FOREIGN KEY (id) REFERENCES systems(id))""", 

93 """CREATE TABLE number_key_values ( 

94 key TEXT, 

95 value REAL, 

96 id INTEGER, 

97 FOREIGN KEY (id) REFERENCES systems(id))""", 

98 """CREATE TABLE information ( 

99 name TEXT, 

100 value TEXT)""", 

101 f"INSERT INTO information VALUES ('version', '{VERSION}')", 

102] 

103 

104index_statements = [ 

105 'CREATE INDEX unique_id_index ON systems(unique_id)', 

106 'CREATE INDEX ctime_index ON systems(ctime)', 

107 'CREATE INDEX username_index ON systems(username)', 

108 'CREATE INDEX calculator_index ON systems(calculator)', 

109 'CREATE INDEX species_index ON species(Z)', 

110 'CREATE INDEX key_index ON keys(key)', 

111 'CREATE INDEX text_index ON text_key_values(key)', 

112 'CREATE INDEX number_index ON number_key_values(key)', 

113] 

114 

115all_tables = [ 

116 'systems', 

117 'species', 

118 'keys', 

119 'text_key_values', 

120 'number_key_values', 

121] 

122 

123 

124def float_if_not_none(x): 

125 """Convert numpy.float64 to float - old db-interfaces need that.""" 

126 if x is not None: 

127 return float(x) 

128 

129 

130class SQLite3Database(Database): 

131 type = 'db' 

132 initialized = False 

133 _allow_reading_old_format = False 

134 default = 'NULL' # used for autoincrement id 

135 connection = None 

136 version = None 

137 columnnames = [ 

138 line.split()[0].lstrip() for line in init_statements[0].splitlines()[1:] 

139 ] 

140 

141 def encode(self, obj, binary=False): 

142 if binary: 

143 return object_to_bytes(obj) 

144 return ase.io.jsonio.encode(obj) 

145 

146 def decode(self, txt, lazy=False): 

147 if lazy: 

148 return txt 

149 if isinstance(txt, str): 

150 return ase.io.jsonio.decode(txt) 

151 return bytes_to_object(txt) 

152 

153 def blob(self, array, dtype=float): 

154 """Convert array to blob/buffer object of the given dtype. 

155 

156 *dtype* must be the dtype that deblob() will use when reading 

157 the value back from the database. The written array will be cast 

158 to this type when NumPy's 'same_kind' casting rule allows it.""" 

159 

160 if array is None: 

161 return None 

162 dtype = np.dtype(dtype) 

163 if len(array) == 0: 

164 array = np.zeros(0, dtype) 

165 if array.dtype != dtype: 

166 if not np.can_cast(array.dtype, dtype, casting='same_kind'): 

167 raise ValueError( 

168 f'Refusing to write array of dtype {array.dtype} to a ' 

169 f'database field of different kind {dtype}' 

170 ) 

171 array = array.astype(dtype) 

172 if not np.little_endian: 

173 array = array.byteswap() 

174 return memoryview(np.ascontiguousarray(array)) 

175 

176 def deblob(self, buf, dtype=float, shape=None): 

177 """Convert blob/buffer object to ndarray of correct dtype and shape. 

178 

179 (without creating an extra view).""" 

180 if buf is None: 

181 return None 

182 if len(buf) == 0: 

183 array = np.zeros(0, dtype) 

184 else: 

185 array = np.frombuffer(buf, dtype) 

186 if not np.little_endian: 

187 array = array.byteswap() 

188 if shape is not None: 

189 array = array.reshape(shape) 

190 return array 

191 

192 def _connect(self): 

193 return sqlite3.connect(self.filename, timeout=20) 

194 

195 def __enter__(self): 

196 assert self.connection is None 

197 self.change_count = 0 

198 self.connection = self._connect() 

199 return self 

200 

201 def __exit__(self, exc_type, exc_value, tb): 

202 if exc_type is None: 

203 self.connection.commit() 

204 else: 

205 self.connection.rollback() 

206 self.connection.close() 

207 self.connection = None 

208 

209 @contextmanager 

210 def managed_connection(self, commit_frequency=5000): 

211 from contextlib import ExitStack 

212 

213 with ExitStack() as stack: 

214 con = self.connection or stack.enter_context(self._connect()) 

215 self._initialize(con) 

216 yield con 

217 

218 if self.connection is None: 

219 con.commit() 

220 else: 

221 self.change_count += 1 

222 if self.change_count % commit_frequency == 0: 

223 con.commit() 

224 

225 def _initialize(self, con): 

226 if self.initialized: 

227 return 

228 

229 self._metadata = {} 

230 

231 cur = con.execute( 

232 "SELECT COUNT(*) FROM sqlite_master WHERE name='systems'" 

233 ) 

234 

235 if cur.fetchone()[0] == 0: 

236 for statement in init_statements: 

237 con.execute(statement) 

238 if self.create_indices: 

239 for statement in index_statements: 

240 con.execute(statement) 

241 con.commit() 

242 self.version = VERSION 

243 else: 

244 cur = con.execute( 

245 "SELECT COUNT(*) FROM sqlite_master WHERE name='user_index'" 

246 ) 

247 if cur.fetchone()[0] == 1: 

248 # Old version with "user" instead of "username" column 

249 self.version = 1 

250 else: 

251 try: 

252 cur = con.execute( 

253 "SELECT value FROM information WHERE name='version'" 

254 ) 

255 except sqlite3.OperationalError: 

256 self.version = 2 

257 else: 

258 self.version = int(cur.fetchone()[0]) 

259 

260 cur = con.execute( 

261 "SELECT value FROM information WHERE name='metadata'" 

262 ) 

263 results = cur.fetchall() 

264 if results: 

265 self._metadata = json.loads(results[0][0]) 

266 

267 if self.version > VERSION: 

268 raise OSError( 

269 f'Can not read new ase.db format (version {self.version}). ' 

270 'Please update to latest ASE.' 

271 ) 

272 if self.version < 5 and not self._allow_reading_old_format: 

273 raise OSError( 

274 'Please convert to new format. ' 

275 f'Use: python -m ase.db.convert {self.filename}' 

276 ) 

277 

278 self.initialized = True 

279 

280 def _write(self, atoms, key_value_pairs, data, id): 

281 ext_tables = key_value_pairs.pop('external_tables', {}) 

282 Database._write(self, atoms, key_value_pairs, data) 

283 

284 mtime = now() 

285 

286 encode = self.encode 

287 blob = self.blob 

288 

289 if not isinstance(atoms, AtomsRow): 

290 row = AtomsRow(atoms) 

291 row.ctime = mtime 

292 row.user = os.getenv('USER') 

293 else: 

294 row = atoms 

295 # Extract the external tables from AtomsRow 

296 names = self._get_external_table_names() 

297 for name in names: 

298 new_table = row.get(name, {}) 

299 if new_table: 

300 ext_tables[name] = new_table 

301 

302 if not id and not key_value_pairs and not ext_tables: 

303 key_value_pairs = row.key_value_pairs 

304 

305 for k, v in ext_tables.items(): 

306 dtype = self._guess_type(v) 

307 self._create_table_if_not_exists(k, dtype) 

308 

309 constraints = row._constraints 

310 if constraints: 

311 if isinstance(constraints, list): 

312 constraints = encode(constraints) 

313 else: 

314 constraints = None 

315 

316 values = ( 

317 row.unique_id, 

318 row.ctime, 

319 mtime, 

320 row.user, 

321 blob(row.numbers, np.int32), 

322 blob(row.positions), 

323 blob(row.cell), 

324 int(np.dot(row.pbc, [1, 2, 4])), 

325 blob(row.get('initial_magmoms')), 

326 blob(row.get('initial_charges')), 

327 blob(row.get('masses')), 

328 blob(row.get('tags'), np.int32), 

329 blob(row.get('momenta')), 

330 constraints, 

331 ) 

332 

333 if 'calculator' in row: 

334 values += (row.calculator, encode(row.calculator_parameters)) 

335 else: 

336 values += (None, None) 

337 

338 if not data: 

339 data = row._data 

340 

341 with self.managed_connection() as con: 

342 if not isinstance(data, (str, bytes)): 

343 data = encode(data, binary=self.version >= 9) 

344 

345 values += ( 

346 float_if_not_none(row.get('energy')), 

347 float_if_not_none(row.get('free_energy')), 

348 blob(row.get('forces')), 

349 blob(row.get('stress')), 

350 blob(row.get('dipole')), 

351 blob(row.get('magmoms')), 

352 row.get('magmom'), 

353 blob(row.get('charges')), 

354 encode(key_value_pairs), 

355 data, 

356 len(row.numbers), 

357 float_if_not_none(row.get('fmax')), 

358 float_if_not_none(row.get('smax')), 

359 float_if_not_none(row.get('volume')), 

360 float(row.mass), 

361 float(row.charge), 

362 ) 

363 

364 cur = con.cursor() 

365 if id is None: 

366 q = self.default + ', ' + ', '.join('?' * len(values)) 

367 cur.execute(f'INSERT INTO systems VALUES ({q})', values) 

368 id = self.get_last_id(cur) 

369 else: 

370 self._delete( 

371 cur, 

372 [id], 

373 ['keys', 'text_key_values', 'number_key_values', 'species'], 

374 ) 

375 q = ', '.join(name + '=?' for name in self.columnnames[1:]) 

376 cur.execute( 

377 f'UPDATE systems SET {q} WHERE id=?', values + (id,) 

378 ) 

379 

380 count = row.count_atoms() 

381 if count: 

382 species = [ 

383 (atomic_numbers[symbol], n, id) 

384 for symbol, n in count.items() 

385 ] 

386 cur.executemany('INSERT INTO species VALUES (?, ?, ?)', species) 

387 

388 text_key_values = [] 

389 number_key_values = [] 

390 for key, value in key_value_pairs.items(): 

391 if isinstance(value, (numbers.Real, np.bool_)): 

392 number_key_values.append([key, float(value), id]) 

393 else: 

394 assert isinstance(value, str) 

395 text_key_values.append([key, value, id]) 

396 

397 cur.executemany( 

398 'INSERT INTO text_key_values VALUES (?, ?, ?)', text_key_values 

399 ) 

400 cur.executemany( 

401 'INSERT INTO number_key_values VALUES (?, ?, ?)', 

402 number_key_values, 

403 ) 

404 cur.executemany( 

405 'INSERT INTO keys VALUES (?, ?)', 

406 [(key, id) for key in key_value_pairs], 

407 ) 

408 

409 # Insert entries in the valid tables 

410 for tabname in ext_tables.keys(): 

411 entries = ext_tables[tabname] 

412 entries['id'] = id 

413 self._insert_in_external_table( 

414 cur, name=tabname, entries=ext_tables[tabname] 

415 ) 

416 

417 return id 

418 

419 def _update(self, id, key_value_pairs, data=None): 

420 """Update key_value_pairs and data for a single row""" 

421 encode = self.encode 

422 ext_tables = key_value_pairs.pop('external_tables', {}) 

423 

424 for k, v in ext_tables.items(): 

425 dtype = self._guess_type(v) 

426 self._create_table_if_not_exists(k, dtype) 

427 

428 mtime = now() 

429 with self.managed_connection() as con: 

430 cur = con.cursor() 

431 cur.execute( 

432 'UPDATE systems SET mtime=?, key_value_pairs=? WHERE id=?', 

433 (mtime, encode(key_value_pairs), id), 

434 ) 

435 if data: 

436 if not isinstance(data, (str, bytes)): 

437 data = encode(data, binary=self.version >= 9) 

438 cur.execute('UPDATE systems set data=? where id=?', (data, id)) 

439 

440 self._delete( 

441 cur, [id], ['keys', 'text_key_values', 'number_key_values'] 

442 ) 

443 

444 text_key_values = [] 

445 number_key_values = [] 

446 for key, value in key_value_pairs.items(): 

447 if isinstance(value, (numbers.Real, np.bool_)): 

448 number_key_values.append([key, float(value), id]) 

449 else: 

450 assert isinstance(value, str) 

451 text_key_values.append([key, value, id]) 

452 

453 cur.executemany( 

454 'INSERT INTO text_key_values VALUES (?, ?, ?)', text_key_values 

455 ) 

456 cur.executemany( 

457 'INSERT INTO number_key_values VALUES (?, ?, ?)', 

458 number_key_values, 

459 ) 

460 cur.executemany( 

461 'INSERT INTO keys VALUES (?, ?)', 

462 [(key, id) for key in key_value_pairs], 

463 ) 

464 

465 # Insert entries in the valid tables 

466 for tabname in ext_tables.keys(): 

467 entries = ext_tables[tabname] 

468 entries['id'] = id 

469 self._insert_in_external_table( 

470 cur, name=tabname, entries=ext_tables[tabname] 

471 ) 

472 

473 return id 

474 

475 def get_last_id(self, cur): 

476 cur.execute("SELECT seq FROM sqlite_sequence WHERE name='systems'") 

477 result = cur.fetchone() 

478 if result is not None: 

479 id = result[0] 

480 return id 

481 else: 

482 return 0 

483 

484 def _get_row(self, id): 

485 with self.managed_connection() as con: 

486 cur = con.cursor() 

487 if id is None: 

488 cur.execute('SELECT COUNT(*) FROM systems') 

489 assert cur.fetchone()[0] == 1 

490 cur.execute('SELECT * FROM systems') 

491 else: 

492 cur.execute('SELECT * FROM systems WHERE id=?', (id,)) 

493 values = cur.fetchone() 

494 

495 return self._convert_tuple_to_row(values) 

496 

497 def _convert_tuple_to_row(self, values): 

498 deblob = self.deblob 

499 decode = self.decode 

500 

501 values = self._old2new(values) 

502 dct = { 

503 'id': values[0], 

504 'unique_id': values[1], 

505 'ctime': values[2], 

506 'mtime': values[3], 

507 'user': values[4], 

508 'numbers': deblob(values[5], np.int32), 

509 'positions': deblob(values[6], shape=(-1, 3)), 

510 'cell': deblob(values[7], shape=(3, 3)), 

511 } 

512 

513 if values[8] is not None: 

514 dct['pbc'] = (values[8] & np.array([1, 2, 4])).astype(bool) 

515 if values[9] is not None: 

516 dct['initial_magmoms'] = deblob(values[9]) 

517 if values[10] is not None: 

518 dct['initial_charges'] = deblob(values[10]) 

519 if values[11] is not None: 

520 dct['masses'] = deblob(values[11]) 

521 if values[12] is not None: 

522 dct['tags'] = deblob(values[12], np.int32) 

523 if values[13] is not None: 

524 dct['momenta'] = deblob(values[13], shape=(-1, 3)) 

525 if values[14] is not None: 

526 dct['constraints'] = values[14] 

527 if values[15] is not None: 

528 dct['calculator'] = values[15] 

529 if values[16] is not None: 

530 dct['calculator_parameters'] = decode(values[16]) 

531 if values[17] is not None: 

532 dct['energy'] = values[17] 

533 if values[18] is not None: 

534 dct['free_energy'] = values[18] 

535 if values[19] is not None: 

536 dct['forces'] = deblob(values[19], shape=(-1, 3)) 

537 if values[20] is not None: 

538 dct['stress'] = deblob(values[20]) 

539 if values[21] is not None: 

540 dct['dipole'] = deblob(values[21]) 

541 if values[22] is not None: 

542 dct['magmoms'] = deblob(values[22]) 

543 if values[23] is not None: 

544 dct['magmom'] = values[23] 

545 if values[24] is not None: 

546 dct['charges'] = deblob(values[24]) 

547 if values[25] != '{}': 

548 dct['key_value_pairs'] = decode(values[25]) 

549 if len(values) >= 27 and values[26] != 'null': 

550 dct['data'] = decode(values[26], lazy=True) 

551 

552 # Now we need to update with info from the external tables 

553 external_tab = self._get_external_table_names() 

554 tables = {} 

555 for tab in external_tab: 

556 row = self._read_external_table(tab, dct['id']) 

557 tables[tab] = row 

558 

559 dct.update(tables) 

560 return AtomsRow(dct) 

561 

562 def _old2new(self, values): 

563 if self.type == 'postgresql': 

564 assert self.version >= 8, 'Your db-version is too old!' 

565 assert self.version >= 4, 'Your db-file is too old!' 

566 if self.version < 5: 

567 pass # should be ok for reading by convert.py script 

568 if self.version < 6: 

569 m = values[23] 

570 if m is not None and not isinstance(m, float): 

571 magmom = float(self.deblob(m, shape=())) 

572 values = values[:23] + (magmom,) + values[24:] 

573 return values 

574 

575 def create_select_statement( 

576 self, 

577 keys, 

578 cmps, 

579 sort=None, 

580 order=None, 

581 sort_table=None, 

582 what='systems.*', 

583 ): 

584 tables = ['systems'] 

585 where = [] 

586 args = [] 

587 for key in keys: 

588 if key == 'forces': 

589 where.append('systems.fmax IS NOT NULL') 

590 elif key == 'strain': 

591 where.append('systems.smax IS NOT NULL') 

592 elif key in ['energy', 'fmax', 'smax', 'constraints', 'calculator']: 

593 where.append(f'systems.{key} IS NOT NULL') 

594 else: 

595 if '-' not in key: 

596 q = 'systems.id in (select id from keys where key=?)' 

597 else: 

598 key = key.replace('-', '') 

599 q = 'systems.id not in (select id from keys where key=?)' 

600 where.append(q) 

601 args.append(key) 

602 

603 # Special handling of "H=0" and "H<2" type of selections: 

604 bad = {} 

605 for key, op, value in cmps: 

606 if isinstance(key, int): 

607 bad[key] = bad.get(key, True) and ops[op](0, value) 

608 

609 for key, op, value in cmps: 

610 if key in [ 

611 'id', 

612 'energy', 

613 'magmom', 

614 'ctime', 

615 'user', 

616 'calculator', 

617 'natoms', 

618 'pbc', 

619 'unique_id', 

620 'fmax', 

621 'smax', 

622 'volume', 

623 'mass', 

624 'charge', 

625 ]: 

626 if key == 'user': 

627 key = 'username' 

628 elif key == 'pbc': 

629 assert op in ['=', '!='] 

630 value = int(np.dot([x == 'T' for x in value], [1, 2, 4])) 

631 elif key == 'magmom': 

632 assert self.version >= 6, 'Update your db-file' 

633 where.append(f'systems.{key}{op}?') 

634 args.append(value) 

635 elif isinstance(key, int): 

636 if self.type == 'postgresql': 

637 where.append( 

638 'cardinality(array_positions(' 

639 + f'numbers::int[], ?)){op}?' 

640 ) 

641 args += [key, value] 

642 else: 

643 if bad[key]: 

644 where.append( 

645 'systems.id not in (select id from species ' 

646 + f'where Z=? and n{invop[op]}?)' 

647 ) 

648 args += [key, value] 

649 else: 

650 where.append( 

651 'systems.id in (select id from species ' 

652 + f'where Z=? and n{op}?)' 

653 ) 

654 args += [key, value] 

655 

656 elif self.type == 'postgresql': 

657 jsonop = '->' 

658 if isinstance(value, str): 

659 jsonop = '->>' 

660 elif isinstance(value, bool): 

661 jsonop = '->>' 

662 value = str(value).lower() 

663 where.append( 

664 "systems.key_value_pairs {} '{}'{}?".format(jsonop, key, op) 

665 ) 

666 args.append(str(value)) 

667 

668 elif isinstance(value, str): 

669 where.append( 

670 'systems.id in (select id from text_key_values ' 

671 + f'where key=? and value{op}?)' 

672 ) 

673 args += [key, value] 

674 else: 

675 where.append( 

676 'systems.id in (select id from number_key_values ' 

677 + f'where key=? and value{op}?)' 

678 ) 

679 args += [key, float(value)] 

680 

681 if sort: 

682 if sort_table != 'systems': 

683 tables.append(f'{sort_table} AS sort_table') 

684 where.append('systems.id=sort_table.id AND sort_table.key=?') 

685 args.append(sort) 

686 sort_table = 'sort_table' 

687 sort = 'value' 

688 

689 sql = f'SELECT {what} FROM\n ' + ', '.join(tables) 

690 if where: 

691 sql += '\n WHERE\n ' + ' AND\n '.join(where) 

692 if sort: 

693 # XXX use "?" instead of "{}" 

694 sql += '\nORDER BY {0}.{1} IS NULL, {0}.{1} {2}'.format( 

695 sort_table, sort, order 

696 ) 

697 

698 return sql, args 

699 

700 def _select( 

701 self, 

702 keys, 

703 cmps, 

704 explain=False, 

705 verbosity=0, 

706 limit=None, 

707 offset=0, 

708 sort=None, 

709 include_data=True, 

710 columns='all', 

711 ): 

712 values = np.array([None for _ in range(27)]) 

713 values[25] = '{}' 

714 values[26] = 'null' 

715 

716 if columns == 'all': 

717 columnindex = list(range(26)) 

718 else: 

719 columnindex = [ 

720 c for c in range(26) if self.columnnames[c] in columns 

721 ] 

722 if include_data: 

723 columnindex.append(26) 

724 

725 if sort: 

726 if sort[0] == '-': 

727 order = 'DESC' 

728 sort = sort[1:] 

729 else: 

730 order = 'ASC' 

731 if sort in [ 

732 'id', 

733 'energy', 

734 'username', 

735 'calculator', 

736 'ctime', 

737 'mtime', 

738 'magmom', 

739 'pbc', 

740 'fmax', 

741 'smax', 

742 'volume', 

743 'mass', 

744 'charge', 

745 'natoms', 

746 ]: 

747 sort_table = 'systems' 

748 else: 

749 for dct in self._select( 

750 keys + [sort], 

751 cmps=[], 

752 limit=1, 

753 include_data=False, 

754 columns=['key_value_pairs'], 

755 ): 

756 if isinstance(dct['key_value_pairs'][sort], str): 

757 sort_table = 'text_key_values' 

758 else: 

759 sort_table = 'number_key_values' 

760 break 

761 else: 

762 # No rows. Just pick a table: 

763 sort_table = 'number_key_values' 

764 

765 else: 

766 order = None 

767 sort_table = None 

768 

769 what = ', '.join( 

770 'systems.' + name 

771 for name in np.array(self.columnnames)[np.array(columnindex)] 

772 ) 

773 

774 sql, args = self.create_select_statement( 

775 keys, cmps, sort, order, sort_table, what 

776 ) 

777 

778 if explain: 

779 sql = 'EXPLAIN QUERY PLAN ' + sql 

780 

781 if limit: 

782 sql += f'\nLIMIT {limit}' 

783 

784 if offset: 

785 sql += self.get_offset_string(offset, limit=limit) 

786 

787 if verbosity == 2: 

788 print(sql, args) 

789 

790 with self.managed_connection() as con: 

791 cur = con.cursor() 

792 cur.execute(sql, args) 

793 if explain: 

794 for row in cur.fetchall(): 

795 yield {'explain': row} 

796 else: 

797 n = 0 

798 for shortvalues in cur.fetchall(): 

799 values[columnindex] = shortvalues 

800 yield self._convert_tuple_to_row(tuple(values)) 

801 n += 1 

802 

803 if sort and sort_table != 'systems': 

804 # Yield rows without sort key last: 

805 if limit is not None: 

806 if n == limit: 

807 return 

808 limit -= n 

809 for row in self._select( 

810 keys + ['-' + sort], 

811 cmps, 

812 limit=limit, 

813 offset=offset, 

814 include_data=include_data, 

815 columns=columns, 

816 ): 

817 yield row 

818 

819 def get_offset_string(self, offset, limit=None): 

820 sql = '' 

821 if not limit: 

822 # In sqlite you cannot have offset without limit, so we 

823 # set it to -1 meaning no limit 

824 sql += '\nLIMIT -1' 

825 sql += f'\nOFFSET {offset}' 

826 return sql 

827 

828 @parallel_function 

829 def count(self, selection=None, **kwargs): 

830 keys, cmps = parse_selection(selection, **kwargs) 

831 sql, args = self.create_select_statement(keys, cmps, what='COUNT(*)') 

832 

833 with self.managed_connection() as con: 

834 cur = con.cursor() 

835 cur.execute(sql, args) 

836 return cur.fetchone()[0] 

837 

838 def analyse(self): 

839 with self.managed_connection() as con: 

840 con.execute('ANALYZE') 

841 

842 @parallel_function 

843 @lock 

844 def delete(self, ids): 

845 if len(ids) == 0: 

846 return 

847 table_names = self._get_external_table_names() + all_tables[::-1] 

848 with self.managed_connection() as con: 

849 self._delete(con.cursor(), ids, tables=table_names) 

850 self.vacuum() 

851 

852 def _delete(self, cur, ids, tables=None): 

853 tables = tables or all_tables[::-1] 

854 for table in tables: 

855 cur.execute( 

856 'DELETE FROM {} WHERE id in ({});'.format( 

857 table, ', '.join([str(id) for id in ids]) 

858 ) 

859 ) 

860 

861 def vacuum(self): 

862 if self.type != 'db': 

863 return 

864 

865 with self.managed_connection() as con: 

866 con.commit() 

867 con.cursor().execute('VACUUM') 

868 

869 @property 

870 def metadata(self): 

871 if self._metadata is None: 

872 with self.managed_connection() as con: 

873 self._initialize(con) 

874 return self._metadata.copy() 

875 

876 @metadata.setter 

877 def metadata(self, dct): 

878 self._metadata = dct 

879 md = json.dumps(dct) 

880 with self.managed_connection() as con: 

881 cur = con.cursor() 

882 cur.execute( 

883 "SELECT COUNT(*) FROM information WHERE name='metadata'" 

884 ) 

885 

886 if cur.fetchone()[0]: 

887 cur.execute( 

888 "UPDATE information SET value=? WHERE name='metadata'", [md] 

889 ) 

890 else: 

891 cur.execute( 

892 'INSERT INTO information VALUES (?, ?)', ('metadata', md) 

893 ) 

894 

895 def _get_external_table_names(self, db_con=None): 

896 """Return a list with the external table names.""" 

897 sql = "SELECT value FROM information WHERE name='external_table_name'" 

898 with self.managed_connection() as con: 

899 cur = con.cursor() 

900 cur.execute(sql) 

901 ext_tab_names = [x[0] for x in cur.fetchall()] 

902 return ext_tab_names 

903 

904 def _external_table_exists(self, name): 

905 """Return True if an external table name exists.""" 

906 return name in self._get_external_table_names() 

907 

908 def _create_table_if_not_exists(self, name, dtype): 

909 """Create a new table if it does not exits. 

910 

911 Arguments 

912 ========== 

913 name: str 

914 Name of the new table 

915 dtype: str 

916 Datatype of the value field (typically REAL, INTEGER, TEXT etc.) 

917 """ 

918 

919 taken_names = set(all_tables + all_properties + self.columnnames) 

920 if name in taken_names: 

921 raise ValueError(f'External table can not be any of {taken_names}') 

922 

923 if self._external_table_exists(name): 

924 return 

925 

926 sql = f'CREATE TABLE IF NOT EXISTS {name} ' 

927 sql += f'(key TEXT, value {dtype}, id INTEGER, ' 

928 sql += 'FOREIGN KEY (id) REFERENCES systems(id))' 

929 sql2 = 'INSERT INTO information VALUES (?, ?)' 

930 with self.managed_connection() as con: 

931 cur = con.cursor() 

932 cur.execute(sql) 

933 # Insert an entry saying that there is a new external table 

934 # present and an entry with the datatype 

935 cur.execute(sql2, ('external_table_name', name)) 

936 cur.execute(sql2, (name + '_dtype', dtype)) 

937 

938 def delete_external_table(self, name): 

939 """Delete an external table.""" 

940 if not self._external_table_exists(name): 

941 return 

942 

943 with self.managed_connection() as con: 

944 cur = con.cursor() 

945 

946 sql = f'DROP TABLE {name}' 

947 cur.execute(sql) 

948 

949 sql = 'DELETE FROM information WHERE value=?' 

950 cur.execute(sql, (name,)) 

951 sql = 'DELETE FROM information WHERE name=?' 

952 cur.execute(sql, (name + '_dtype',)) 

953 

954 def _convert_to_recognized_types(self, value): 

955 """Convert Numpy types to python types.""" 

956 if np.issubdtype(type(value), np.integer): 

957 return int(value) 

958 elif np.issubdtype(type(value), np.floating): 

959 return float(value) 

960 return value 

961 

962 def _insert_in_external_table(self, cursor, name=None, entries=None): 

963 """Insert into external table""" 

964 if name is None or entries is None: 

965 # There is nothing to do 

966 return 

967 

968 id = entries.pop('id') 

969 dtype = self._guess_type(entries) 

970 expected_dtype = self._get_value_type_of_table(cursor, name) 

971 if dtype != expected_dtype: 

972 raise ValueError( 

973 f'The provided data type for table {name} is {dtype}, while ' 

974 f'it is initialized to be of type {expected_dtype}' 

975 ) 

976 

977 # First we check if entries already exists 

978 cursor.execute(f'SELECT key FROM {name} WHERE id=?', (id,)) 

979 updates = [] 

980 for item in cursor.fetchall(): 

981 value = entries.pop(item[0], None) 

982 if value is not None: 

983 updates.append( 

984 (value, id, self._convert_to_recognized_types(item[0])) 

985 ) 

986 

987 # Update entry if key and ID already exists 

988 sql = f'UPDATE {name} SET value=? WHERE id=? AND key=?' 

989 cursor.executemany(sql, updates) 

990 

991 # Insert the ones that does not already exist 

992 inserts = [ 

993 (k, self._convert_to_recognized_types(v), id) 

994 for k, v in entries.items() 

995 ] 

996 sql = f'INSERT INTO {name} VALUES (?, ?, ?)' 

997 cursor.executemany(sql, inserts) 

998 

999 def _guess_type(self, entries): 

1000 """Guess the type based on the first entry.""" 

1001 values = [v for _, v in entries.items()] 

1002 

1003 # Check if all datatypes are the same 

1004 all_types = [type(v) for v in values] 

1005 if any(t != all_types[0] for t in all_types): 

1006 typenames = [t.__name__ for t in all_types] 

1007 raise ValueError( 

1008 f'Inconsistent datatypes in the table. given types: {typenames}' 

1009 ) 

1010 

1011 val = values[0] 

1012 if isinstance(val, int) or np.issubdtype(type(val), np.integer): 

1013 return 'INTEGER' 

1014 if isinstance(val, float) or np.issubdtype(type(val), np.floating): 

1015 return 'REAL' 

1016 if isinstance(val, str): 

1017 return 'TEXT' 

1018 raise ValueError('Unknown datatype!') 

1019 

1020 def _get_value_type_of_table(self, cursor, tab_name): 

1021 """Return the expected value name.""" 

1022 sql = 'SELECT value FROM information WHERE name=?' 

1023 cursor.execute(sql, (tab_name + '_dtype',)) 

1024 return cursor.fetchone()[0] 

1025 

1026 def _read_external_table(self, name, id): 

1027 """Read row from external table.""" 

1028 

1029 with self.managed_connection() as con: 

1030 cur = con.cursor() 

1031 cur.execute(f'SELECT * FROM {name} WHERE id=?', (id,)) 

1032 items = cur.fetchall() 

1033 dictionary = {item[0]: item[1] for item in items} 

1034 

1035 return dictionary 

1036 

1037 def get_all_key_names(self): 

1038 """Create set of all key names.""" 

1039 with self.managed_connection() as con: 

1040 cur = con.cursor() 

1041 cur.execute('SELECT DISTINCT key FROM keys;') 

1042 all_keys = {row[0] for row in cur.fetchall()} 

1043 return all_keys 

1044 

1045 

1046if __name__ == '__main__': 

1047 from ase.db import connect 

1048 

1049 con = connect(sys.argv[1]) 

1050 con._initialize(con._connect()) 

1051 print('Version:', con.version)