-
-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathutils.cpp
More file actions
464 lines (407 loc) · 16.1 KB
/
Copy pathutils.cpp
File metadata and controls
464 lines (407 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
#include "utils.hpp"
#include "SmartHostObject.hpp"
#include "types.hpp"
#ifndef OP_SQLITE_USE_LIBSQL
#include "bridge.hpp"
#endif
#include "OPThreadPool.hpp"
#include "macros.hpp"
#include <fstream>
#include <sys/stat.h>
#include <utility>
namespace opsqlite {
namespace jsi = facebook::jsi;
namespace react = facebook::react;
jsi::Value to_jsi(jsi::Runtime &rt, const JSVariant &value) {
if (std::holds_alternative<bool>(value)) {
return std::get<bool>(value);
} else if (std::holds_alternative<int>(value)) {
return jsi::Value(std::get<int>(value));
} else if (std::holds_alternative<long long>(value)) {
return jsi::Value(static_cast<double>(std::get<long long>(value)));
} else if (std::holds_alternative<double>(value)) {
return jsi::Value(std::get<double>(value));
} else if (std::holds_alternative<std::string>(value)) {
auto str = std::get<std::string>(value);
return jsi::String::createFromUtf8(rt, str);
} else if (std::holds_alternative<ArrayBuffer>(value)) {
auto jsBuffer = std::get<ArrayBuffer>(value);
jsi::Function array_buffer_ctor =
rt.global().getPropertyAsFunction(rt, "ArrayBuffer");
jsi::Object o = array_buffer_ctor.callAsConstructor(rt, (int)jsBuffer.size)
.getObject(rt);
jsi::ArrayBuffer buf = o.getArrayBuffer(rt);
memcpy(buf.data(rt), jsBuffer.data.get(), jsBuffer.size);
return o;
}
return jsi::Value::null();
// I wanted to use the visitor pattern here but on the ArrayBuffer case it
// is somehow throwing a pointer exception Somehow the v.size or
// v.data.get() is loosing the data when called from the lambda I'm guessing
// the I created the shared pointer wrong and the memory is being freed
// before the lambda is called
// return std::visit(
// [&](auto &&v) -> jsi::Value {
// using T = std::decay_t<decltype(v)>;
// if constexpr (std::is_same_v<T, bool>) {
// return jsi::Value(v);
// } else if constexpr (std::is_same_v<T, int>) {
// return jsi::Value(v);
// } else if constexpr (std::is_same_v<T, long long>) {
// return jsi::Value(
// static_cast<double>(v)); // JSI doesn't support long long
// } else if constexpr (std::is_same_v<T, double>) {
// return jsi::Value(v);
// } else if constexpr (std::is_same_v<T, std::string>) {
// return jsi::String::createFromUtf8(rt, v);
// } else if constexpr (std::is_same_v<T, ArrayBuffer>) {
// static jsi::Function buffer_constructor =
// rt.global().getPropertyAsFunction(rt, "ArrayBuffer");
// jsi::Object o =
// buffer_constructor.callAsConstructor(rt,
// static_cast<int>(v.size))
// .getObject(rt);
// jsi::ArrayBuffer buf = o.getArrayBuffer(rt);
// memcpy(buf.data(rt), v.data.get(), v.size);
// return o;
// } else {
// return jsi::Value::null();
// }
// },
// value);
}
JSVariant to_variant(jsi::Runtime &rt, const jsi::Value &value) {
if (value.isNull() || value.isUndefined()) {
return JSVariant(nullptr);
} else if (value.isBool()) {
return JSVariant(value.getBool());
} else if (value.isNumber()) {
double doubleVal = value.asNumber();
int intVal = (int)doubleVal;
long long longVal = (long)doubleVal;
if (intVal == doubleVal) {
return JSVariant(intVal);
} else if (longVal == doubleVal) {
return JSVariant(longVal);
} else {
return JSVariant(doubleVal);
}
} else if (value.isString()) {
std::string strVal = value.asString(rt).utf8(rt);
return JSVariant(std::move(strVal));
} else if (value.isObject()) {
auto obj = value.asObject(rt);
size_t byteOffset = 0;
size_t byteLength = 0;
uint8_t *sourceData = nullptr;
jsi::Function arrayBufferCtor =
rt.global().getPropertyAsFunction(rt, "ArrayBuffer");
jsi::Function isViewFn =
arrayBufferCtor.getPropertyAsFunction(rt, "isView");
bool isArrayBufferView = isViewFn.call(rt, obj).getBool();
if (obj.isArrayBuffer(rt)) {
auto buffer = obj.getArrayBuffer(rt);
sourceData = buffer.data(rt);
byteLength = buffer.size(rt);
} else if (isArrayBufferView) {
jsi::Object bufferObject = obj.getPropertyAsObject(rt, "buffer");
auto buffer = bufferObject.getArrayBuffer(rt);
byteOffset =
static_cast<size_t>(obj.getProperty(rt, "byteOffset").asNumber());
byteLength =
static_cast<size_t>(obj.getProperty(rt, "byteLength").asNumber());
const size_t bufferSize = buffer.size(rt);
if (byteOffset > bufferSize || byteLength > bufferSize - byteOffset) {
throw std::runtime_error("Invalid ArrayBuffer view range");
}
sourceData = buffer.data(rt) + byteOffset;
} else {
throw std::runtime_error(
"Object is not an ArrayBuffer or ArrayBuffer view, cannot bind "
"to SQLite");
}
uint8_t *data = new uint8_t[byteLength];
memcpy(data, sourceData, byteLength);
return JSVariant(ArrayBuffer{.data = std::shared_ptr<uint8_t[]>{data},
.size = byteLength});
}
throw std::runtime_error("Cannot convert JSI value to C++ Variant value");
}
std::vector<std::string> to_string_vec(jsi::Runtime &rt, jsi::Value const &xs) {
jsi::Array const values = xs.asObject(rt).asArray(rt);
std::vector<std::string> res;
for (int ii = 0; ii < values.length(rt); ii++) {
std::string value = values.getValueAtIndex(rt, ii).asString(rt).utf8(rt);
res.emplace_back(value);
}
return res;
}
std::vector<int> to_int_vec(jsi::Runtime &rt, jsi::Value const &xs) {
jsi::Array const values = xs.asObject(rt).asArray(rt);
std::vector<int> res;
for (int ii = 0; ii < values.length(rt); ii++) {
int value = static_cast<int>(values.getValueAtIndex(rt, ii).asNumber());
res.emplace_back(value);
}
return res;
}
std::vector<JSVariant> to_variant_vec(jsi::Runtime &rt, jsi::Value const &xs) {
jsi::Array const values = xs.asObject(rt).asArray(rt);
size_t arg_length = values.length(rt);
std::vector<JSVariant> res;
res.reserve(arg_length);
for (size_t ii = 0; ii < arg_length; ii++) {
res.emplace_back(to_variant(rt, values.getValueAtIndex(rt, ii)));
}
return res;
}
jsi::Value create_js_rows(jsi::Runtime &rt, const BridgeResult &status) {
jsi::Object res = jsi::Object(rt);
res.setProperty(rt, "rowsAffected", status.affectedRows);
if (status.affectedRows > 0 && status.insertId != 0) {
res.setProperty(rt, "insertId", jsi::Value(status.insertId));
}
size_t row_count = status.rows.size();
size_t column_count = status.column_names.size();
if (row_count == 0) {
res.setProperty(rt, "rows", jsi::Array(rt, 0));
return res;
}
std::vector<jsi::PropNameID> column_prop_ids;
column_prop_ids.reserve(column_count);
for (size_t i = 0; i < column_count; i++) {
column_prop_ids.emplace_back(
jsi::PropNameID::forUtf8(rt, status.column_names[i]));
}
auto rows = jsi::Array(rt, row_count);
for (int i = 0; i < row_count; i++) {
auto row = jsi::Object(rt);
for (int j = 0; j < column_count; j++) {
row.setProperty(rt, column_prop_ids[j], to_jsi(rt, status.rows[i][j]));
}
rows.setValueAtIndex(rt, i, std::move(row));
}
res.setProperty(rt, "rows", std::move(rows));
return res;
}
jsi::Value
create_result(jsi::Runtime &rt, const BridgeResult &status,
std::vector<DumbHostObject> *results,
std::shared_ptr<std::vector<SmartHostObject>> metadata) {
jsi::Object res = jsi::Object(rt);
res.setProperty(rt, "rowsAffected", status.affectedRows);
if (status.affectedRows > 0 && status.insertId != 0) {
res.setProperty(rt, "insertId", jsi::Value(status.insertId));
}
size_t rowCount = results->size();
auto array = jsi::Array(rt, rowCount);
for (int i = 0; i < rowCount; i++) {
auto obj = results->at(i);
array.setValueAtIndex(rt, i,
jsi::Object::createFromHostObject(
rt, std::make_shared<DumbHostObject>(obj)));
}
res.setProperty(rt, "rows", std::move(array));
size_t column_count = metadata->size();
auto column_array = jsi::Array(rt, column_count);
for (int i = 0; i < column_count; i++) {
auto column = metadata->at(i);
column_array.setValueAtIndex(
rt, i,
jsi::Object::createFromHostObject(
rt, std::make_shared<SmartHostObject>(column)));
}
res.setProperty(rt, "metadata", std::move(column_array));
return std::move(res);
}
jsi::Value
create_raw_result(jsi::Runtime &rt, const BridgeResult &status,
const std::vector<std::vector<JSVariant>> *results) {
size_t row_count = results->size();
jsi::Object res(rt);
jsi::Array raw_rows = jsi::Array(rt, row_count);
for (int i = 0; i < row_count; i++) {
auto row = results->at(i);
auto array = jsi::Array(rt, row.size());
for (int j = 0; j < row.size(); j++) {
array.setValueAtIndex(rt, j, to_jsi(rt, row[j]));
}
raw_rows.setValueAtIndex(rt, i, array);
}
size_t column_count = status.column_names.size();
jsi::Array column_names = jsi::Array(rt, column_count);
for (int i = 0; i < column_count; i++) {
column_names.setValueAtIndex(
rt, i, jsi::String::createFromUtf8(rt, status.column_names.at(i)));
}
res.setProperty(rt, "rowsAffected", status.affectedRows);
res.setProperty(rt, "insertId", status.insertId);
res.setProperty(rt, "rawRows", std::move(raw_rows));
res.setProperty(rt, "columnNames", std::move(column_names));
return res;
}
void to_batch_arguments(jsi::Runtime &rt, jsi::Array const &tuples,
std::vector<BatchArguments> *commands) {
for (int i = 0; i < tuples.length(rt); i++) {
const jsi::Array &tuple =
tuples.getValueAtIndex(rt, i).asObject(rt).asArray(rt);
const size_t length = tuple.length(rt);
if (length == 0) {
continue;
}
const std::string query =
tuple.getValueAtIndex(rt, 0).asString(rt).utf8(rt);
if (length == 1) {
commands->push_back({query});
continue;
}
const jsi::Value &tuple_params = tuple.getValueAtIndex(rt, 1);
if (!tuple_params.isUndefined() && tuple_params.asObject(rt).isArray(rt) &&
tuple_params.asObject(rt).asArray(rt).length(rt) > 0 &&
tuple_params.asObject(rt)
.asArray(rt)
.getValueAtIndex(rt, 0)
.isObject()) {
// The params for this tuple is an array itself
// The query should repeat for each element in the array
const jsi::Array ¶ms_array = tuple_params.asObject(rt).asArray(rt);
for (int x = 0; x < params_array.length(rt); x++) {
const jsi::Value &p = params_array.getValueAtIndex(rt, x);
auto params = std::vector<JSVariant>(to_variant_vec(rt, p));
commands->push_back({query, params});
}
} else {
auto params = std::vector<JSVariant>(to_variant_vec(rt, tuple_params));
commands->push_back({query, params});
}
}
}
#ifndef OP_SQLITE_USE_LIBSQL
BatchResult import_sql_file(sqlite3 *db, std::string path) {
std::string line;
std::ifstream sqFile(path);
if (!sqFile.is_open()) {
throw std::runtime_error("Could not open file: " + path);
}
try {
int affectedRows = 0;
int commands = 0;
opsqlite_execute(db, "BEGIN EXCLUSIVE TRANSACTION", nullptr);
while (std::getline(sqFile, line, '\n')) {
if (!line.empty()) {
try {
auto result = opsqlite_execute(db, line, nullptr);
affectedRows += result.affectedRows;
commands++;
} catch (std::exception &exc) {
opsqlite_execute(db, "ROLLBACK", nullptr);
sqFile.close();
throw exc;
}
}
}
sqFile.close();
opsqlite_execute(db, "COMMIT", nullptr);
return {"", affectedRows, commands};
} catch (std::exception &exc) {
sqFile.close();
opsqlite_execute(db, "ROLLBACK", nullptr);
throw exc;
}
}
#endif
bool folder_exists(const std::string &name) {
struct stat buffer;
return (stat(name.c_str(), &buffer) == 0);
}
bool file_exists(const std::string &path) {
struct stat buffer;
return (stat(path.c_str(), &buffer) == 0);
}
void log_to_console(jsi::Runtime &runtime, const std::string &message) {
auto console = runtime.global().getPropertyAsObject(runtime, "console");
auto log = console.getPropertyAsFunction(runtime, "log");
log.call(runtime, jsi::String::createFromUtf8(runtime, message));
}
jsi::Value
promisify(jsi::Runtime &rt, std::shared_ptr<ThreadPool> thread_pool,
std::function<std::any()> lambda,
std::function<jsi::Value(jsi::Runtime &rt, std::any result)>
resolve_callback) {
auto promise_constructor = rt.global().getPropertyAsFunction(rt, "Promise");
auto executor =
HFN3(lambda = std::move(lambda),
resolve_callback = std::move(resolve_callback), thread_pool) {
auto resolve = std::make_shared<jsi::Value>(rt, args[0]);
auto reject = std::make_shared<jsi::Value>(rt, args[1]);
// Bind this generation's invoker and liveness flag here, on the JS thread,
// while the promise is being constructed. Reading the process globals from
// the worker instead lets a task queued by a torn-down runtime post into the
// runtime that replaced it, and then call asFunction() on a jsi::Value that
// belongs to the dead one.
auto invoker = opsqlite::invoker;
auto alive = opsqlite::generation_alive;
auto task = [lambda = lambda, resolve_callback = resolve_callback,
resolve = std::move(resolve), reject = std::move(reject),
invoker, alive]() {
if (invoker == nullptr) {
return;
}
try {
std::any result = lambda();
// This generation is gone. Posting now would schedule onto a runtime
// that is being torn down, where asFunction() sees an already
// invalidated PointerValue.
if (alive != nullptr && !alive->load()) {
return;
}
// reject is also captured in the invokeAsync lambda
// so it can be safely disposed on the JS thread
invoker->invokeAsync(
[result = std::move(result), resolve = resolve, reject = reject,
resolve_callback = resolve_callback](jsi::Runtime &rt) {
auto jsi_result = resolve_callback(rt, result);
resolve->asObject(rt).asFunction(rt).call(rt, jsi_result);
});
} catch (std::runtime_error &e) {
// On Android RN is broken and does not correctly match
// runtime_error to the generic exception We have to
// explicitly catch it
// https://github.com/facebook/react-native/issues/48027
//
// resolve is also captured in the invokeAsync lambda
// so it can be safely disposed on the JS thread
auto what = e.what();
if (alive != nullptr && !alive->load()) {
return;
}
invoker->invokeAsync([what = std::string(what), resolve = resolve,
reject = reject](jsi::Runtime &rt) {
auto errorCtr = rt.global().getPropertyAsFunction(rt, "Error");
auto error = errorCtr.callAsConstructor(
rt, jsi::String::createFromAscii(rt, what));
reject->asObject(rt).asFunction(rt).call(rt, error);
});
} catch (std::exception &exc) {
auto what = exc.what();
if (alive != nullptr && !alive->load()) {
return;
}
// resolve is also captured in the invokeAsync lambda
// so it can be safely disposed on the JS thread
invoker->invokeAsync([what = std::string(what), resolve = resolve,
reject = reject](jsi::Runtime &rt) {
auto errorCtr = rt.global().getPropertyAsFunction(rt, "Error");
auto error = errorCtr.callAsConstructor(
rt, jsi::String::createFromAscii(rt, what));
reject->asObject(rt).asFunction(rt).call(rt, error);
});
}
};
thread_pool->queue_work(task);
return jsi::Value(nullptr);
});
auto promise = promise_constructor.callAsConstructor(rt, executor);
return promise;
}
} // namespace opsqlite