diff --git a/src/addins/sqlite/Cargo.lock b/src/addins/sqlite/Cargo.lock index 3be5158974..056484b1fd 100644 --- a/src/addins/sqlite/Cargo.lock +++ b/src/addins/sqlite/Cargo.lock @@ -117,6 +117,7 @@ dependencies = [ "addin1c", "base64", "rusqlite", + "serde", "serde_json", "serde_rusqlite", ] diff --git a/src/addins/sqlite/Cargo.toml b/src/addins/sqlite/Cargo.toml index 7689397d55..199ba17df8 100644 --- a/src/addins/sqlite/Cargo.toml +++ b/src/addins/sqlite/Cargo.toml @@ -17,4 +17,5 @@ addin1c = "0.5.0" rusqlite = { version = "0.32.1", features = ["bundled"]} serde_json = "1.0" serde_rusqlite = "0.36.0" -base64 = "0.22.1" \ No newline at end of file +base64 = "0.22.1" +serde = "1.0.217" \ No newline at end of file diff --git a/src/addins/sqlite/src/component/methods.rs b/src/addins/sqlite/src/component/methods.rs index 5e94977757..474a0bea79 100644 --- a/src/addins/sqlite/src/component/methods.rs +++ b/src/addins/sqlite/src/component/methods.rs @@ -4,6 +4,8 @@ use crate::component; use serde_rusqlite::{to_params}; use base64::{engine::general_purpose, Engine as _}; + + pub fn execute_query( client: &mut component::AddIn, query: String, @@ -16,7 +18,7 @@ pub fn execute_query( }; // Парсинг JSON параметров - let parsed_params: Value = match serde_json::from_str(¶ms_json) { + let mut parsed_params: Value = match serde_json::from_str(¶ms_json) { Ok(params) => params, Err(e) => { return format!( @@ -26,15 +28,19 @@ pub fn execute_query( } }; - let params_array = match parsed_params.as_array() { + let params_array = match parsed_params.as_array_mut() { Some(array) => array, None => { return r#"{"result": false, "error": "Parameters must be a JSON array"}"#.to_string(); } }; + process_blobs(params_array); - let convert = to_params(params_array).unwrap(); + let convert = match to_params(params_array){ + Ok(params) => params, + Err(e) => {return format!(r#"{{"result": false, "error": "{}"}}"#, e.to_string())} + }; // Определяем тип запроса if query.trim_start().to_uppercase().starts_with("SELECT") { @@ -105,7 +111,7 @@ fn rows_to_json_array(rows: &mut rusqlite::Rows, cols: &Vec) -> String { } } - json!(json_array).to_string() + json!({ "result": json_array }).to_string() } fn from_sql_to_json(value: ValueRef) -> Value { @@ -123,4 +129,40 @@ fn from_sql_to_json(value: ValueRef) -> Value { Value::Object(blob_object) }, } +} + +fn process_blobs(json_array: &mut Vec) { + + for item in json_array.iter_mut() { + + if let Value::Object(obj) = item { + + // Проверяем, есть ли ключ "blob" + if let Some(Value::String(blob_str)) = obj.get("blob") { + match general_purpose::STANDARD.decode(blob_str) { + Ok(decoded_blob) => { + let current_blob = decoded_blob + .into_iter() + .map(|b| { + if u64::from(b) > i64::MAX as u64 { + Value::Number(serde_json::Number::from(i64::MAX)) + } else { + Value::Number(serde_json::Number::from(b as i64)) + } + }) + .collect::>(); + *item = Value::Array(current_blob); + } + Err(e) => { + // Обработка ошибок декодирования + *item = Value::String(format!("blob_error: {}", e)); + } + } + } + } else if let Value::Array(array) = item { + // Рекурсивно обрабатываем вложенные массивы + process_blobs(array); + } + } + } \ No newline at end of file diff --git a/src/en/OInt/addins/OPI_SQLite.zip b/src/en/OInt/addins/OPI_SQLite.zip index 6b8624c1ec..9684925002 100644 Binary files a/src/en/OInt/addins/OPI_SQLite.zip and b/src/en/OInt/addins/OPI_SQLite.zip differ diff --git a/src/en/OPI/src/CommonTemplates/OPI_SQLite/Template.addin b/src/en/OPI/src/CommonTemplates/OPI_SQLite/Template.addin index 6b8624c1ec..9684925002 100644 Binary files a/src/en/OPI/src/CommonTemplates/OPI_SQLite/Template.addin and b/src/en/OPI/src/CommonTemplates/OPI_SQLite/Template.addin differ diff --git a/src/ru/OInt/addins/OPI_SQLite.zip b/src/ru/OInt/addins/OPI_SQLite.zip index 6b8624c1ec..9684925002 100644 Binary files a/src/ru/OInt/addins/OPI_SQLite.zip and b/src/ru/OInt/addins/OPI_SQLite.zip differ diff --git a/src/ru/OPI/src/CommonModules/OPI_SQLite/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_SQLite/Module.bsl new file mode 100644 index 0000000000..c7cce460d3 --- /dev/null +++ b/src/ru/OPI/src/CommonModules/OPI_SQLite/Module.bsl @@ -0,0 +1,132 @@ +// OneScript: ./OInt/core/Modules/OPI_SQLite.os +// Lib: SQLite +// CLI: sqlite + +// MIT License + +// Copyright (c) 2023 Anton Tsitavets + +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +// https://github.com/Bayselonarrend/OpenIntegrations + +// BSLLS:Typo-off +// BSLLS:LatinAndCyrillicSymbolInWord-off +// BSLLS:IncorrectLineBreak-off +// BSLLS:NumberOfOptionalParams-off +// BSLLS:UsingServiceTag-off +// BSLLS:LineLength-off + +//@skip-check module-structure-top-region +//@skip-check module-structure-method-in-regions +//@skip-check wrong-string-literal-content +//@skip-check method-too-many-params +//@skip-check constructor-function-return-section + +// Раскомментировать, если выполняется OneScript +// #Использовать "../../tools" + +#Область ПрограммныйИнтерфейс + +Функция СоздатьПодключение(Знач База = "") Экспорт + + Если Строка(ТипЗнч(База)) = "AddIn.OPI_SQLite.Main" Тогда + Возврат База; + КонецЕсли; + + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); + + Коннектор = ПодключитьКомпонентуНаСервере("OPI_SQLite"); + + Коннектор.Database = База; + + Результат = Коннектор.Connect(); + Результат = OPI_Инструменты.JsonВСтруктуру(Результат, Ложь); + + Возврат ?(Результат["result"], Коннектор, Результат); + +КонецФункции + +Функция ВыполнитьЗапрос(Знач ТекстЗапроса, Знач Параметры = "", Знач Соединение = "") Экспорт + + OPI_ПреобразованиеТипов.ПолучитьСтроку(ТекстЗапроса); + + Параметры_ = ОбработатьПараметры(Параметры); + Коннектор = СоздатьПодключение(Соединение); + + Если ТипЗнч(Коннектор) <> Тип("AddIn.OPI_SQLite.Main") Тогда + Возврат Коннектор; + КонецЕсли; + + Результат = Коннектор.Execute(ТекстЗапроса, Параметры_); + + Возврат Результат; + +КонецФункции + +#КонецОбласти + +#Область СлужебныеПроцедурыИФункции + +Функция ПодключитьКомпонентуНаСервере(Знач ИмяКомпоненты, Знач Класс = "Main") + + Если OPI_Инструменты.ЭтоOneScript() Тогда + ИмяМакета = OPI_Инструменты.КаталогКомпонентOS() + ИмяКомпоненты + ".zip"; + Иначе + ИмяМакета = "ОбщийМакет." + ИмяКомпоненты; + КонецЕсли; + + ПодключитьВнешнююКомпоненту(ИмяМакета, ИмяКомпоненты, ТипВнешнейКомпоненты.Native); + + Компонента = Новый("AddIn." + ИмяКомпоненты + "." + Класс); + Возврат Компонента; + +КонецФункции + +Функция ОбработатьПараметры(Знач Параметры) + + Если ЗначениеЗаполнено(Параметры) Тогда + + OPI_ПреобразованиеТипов.ПолучитьМассив(Параметры); + + Для Н = 0 По Параметры.ВГраница() Цикл + + ТекущийПараметр = Параметры[Н]; + + Если Не OPI_Инструменты.ЭтоПримитивныйТип(ТекущийПараметр) Тогда + OPI_ПреобразованиеТипов.ПолучитьСтроку(ТекущийПараметр); + КонецЕсли; + + Параметры[Н] = ТекущийПараметр; + + КонецЦикла; + + Параметры_ = OPI_Инструменты.JSONСтрокой(Параметры, , Ложь); + + Иначе + + Параметры_ = "[]"; + + КонецЕсли; + + Возврат Параметры_; + +КонецФункции + +#КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_SQLite/OPI_SQLite.mdo b/src/ru/OPI/src/CommonModules/OPI_SQLite/OPI_SQLite.mdo new file mode 100644 index 0000000000..b5d371174b --- /dev/null +++ b/src/ru/OPI/src/CommonModules/OPI_SQLite/OPI_SQLite.mdo @@ -0,0 +1,11 @@ + + + OPI_SQLite + + + OPI SQLite + + true + true + true + diff --git a/src/ru/OPI/src/CommonModules/OPI_Инструменты/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_Инструменты/Module.bsl index 228c1db06c..2e73c8f982 100644 --- a/src/ru/OPI/src/CommonModules/OPI_Инструменты/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_Инструменты/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/tools/Modules/internal/Modules/OPI_Инструменты.os +// OneScript: ./OInt/tools/Modules/internal/Modules/OPI_Инструменты.os // MIT License @@ -1146,6 +1146,14 @@ КонецФункции +Функция ЭтоПримитивныйТип(Знач Значение) Экспорт + + Возврат ТипЗнч(Значение) = Тип("Строка") + Или ТипЗнч(Значение) = Тип("Число") + Или ТипЗнч(Значение) = Тип("Булево") + +КонецФункции + #КонецОбласти #КонецОбласти diff --git a/src/ru/OPI/src/CommonTemplates/OPI_SQLite/Template.addin b/src/ru/OPI/src/CommonTemplates/OPI_SQLite/Template.addin index 6b8624c1ec..9684925002 100644 Binary files a/src/ru/OPI/src/CommonTemplates/OPI_SQLite/Template.addin and b/src/ru/OPI/src/CommonTemplates/OPI_SQLite/Template.addin differ diff --git a/src/ru/OPI/src/Configuration/Configuration.mdo b/src/ru/OPI/src/Configuration/Configuration.mdo index 41168b860a..f7cc2a48ef 100644 --- a/src/ru/OPI/src/Configuration/Configuration.mdo +++ b/src/ru/OPI/src/Configuration/Configuration.mdo @@ -56,6 +56,7 @@ CommonModule.OPI_Ozon CommonModule.OPI_Notion CommonModule.OPI_Slack + CommonModule.OPI_SQLite CommonModule.OPI_S3 CommonModule.OPI_TCP CommonModule.OPI_Telegram