YARP
Yet Another Robot Platform
TripleSourceCreator.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2006-2021 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-FileCopyrightText: 2006-2010 RobotCub Consortium
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
8
11
12#if !defined(_WIN32)
13#include <unistd.h>
14#else
15#include <io.h>
16#define access(f,a) _access(f,a)
17#endif
18
19#ifndef F_OK
20#define F_OK 0
21#endif
22
23#include <string>
24using namespace yarp::serversql::impl;
25
26
27static bool sql_enact(sqlite3 *db, const char *cmd) {
28 //printf("ISSUE %s\n", cmd);
29 int result = sqlite3_exec(db, cmd, nullptr, nullptr, nullptr);
30 if (result!=SQLITE_OK) {
31 const char *msg = sqlite3_errmsg(db);
32 if (msg != nullptr) {
33 fprintf(stderr,"Database error: %s\n", msg);
34 }
35 sqlite3_close(db);
36 fprintf(stderr,"Failed to set up database tables\n");
37 std::exit(1);
38 }
39 return true;
40}
41
42
43TripleSource *TripleSourceCreator::open(const char *filename,
44 bool cautious,
45 bool fresh) {
46 sqlite3 *db = nullptr;
47 if (fresh) {
48 int result = access(filename,F_OK);
49 if (result==0) {
50 fprintf(stderr,"Database needs to be recreated.\n");
51 fprintf(stderr,"Please move %s out of the way.\n", filename);
52 return nullptr;
53 }
54
55 }
56 int result = sqlite3_open_v2(filename,
57 &db,
58 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_NOMUTEX,
59 nullptr);
60 if (result!=SQLITE_OK) {
61 fprintf(stderr,"Failed to open database %s\n", filename);
62 if (db != nullptr) {
63 sqlite3_close(db);
64 }
65 return nullptr;
66 }
67
68
69 std::string create_main_table = "CREATE TABLE IF NOT EXISTS tags (\n\
70 id INTEGER PRIMARY KEY,\n\
71 rid INTEGER,\n\
72 ns TEXT,\n\
73 name TEXT,\n\
74 value TEXT);";
75
76 result = sqlite3_exec(db, create_main_table.c_str(), nullptr, nullptr, nullptr);
77 if (result!=SQLITE_OK) {
78 const char *msg = sqlite3_errmsg(db);
79 if (msg != nullptr) {
80 fprintf(stderr,"Error in %s: %s\n", filename, msg);
81 }
82 sqlite3_close(db);
83 fprintf(stderr,"Failed to set up database tables\n");
84 std::exit(1);
85 }
86
87 std::string cmd_synch = std::string("PRAGMA synchronous=") + (cautious?"FULL":"OFF") + ";";
88 sql_enact(db,cmd_synch.c_str());
89
90 sql_enact(db,"CREATE INDEX IF NOT EXISTS tagsRidNameValue on tags(rid,name,value);");
91
92 implementation = db;
93 accessor = new SqliteTripleSource(db);
94 return accessor;
95}
96
97
99 if (accessor != nullptr) {
100 delete accessor;
101 accessor = nullptr;
102 }
103 if (implementation != nullptr) {
104 auto* db = (sqlite3 *)implementation;
105 sqlite3_close(db);
106 implementation = nullptr;
107 }
108 return true;
109}
static bool sql_enact(sqlite3 *db, const char *cmd)
#define F_OK
Sqlite database, viewed as a collection of triples.
Abstract view of a database as a collection of triples.
Definition: TripleSource.h:39