diff --git a/sqflite/pubspec.yaml b/sqflite/pubspec.yaml index 99e3b9b554e9faaa343cd02eca6d4e7ede9a1700..e9636abc9e91db12042e9707f467e0694b413c09 100644 --- a/sqflite/pubspec.yaml +++ b/sqflite/pubspec.yaml @@ -51,7 +51,7 @@ dependencies: sqflite_common: git: url: "https://gitee.com/openharmony-sig/flutter_sqflite.git" - path: "sqflite/tripartite/sqflite_common" + path: "sqflite_common" # sqflite_ohos: # path: sqflite_ohos diff --git a/sqflite/tripartite/sqflite_common/.gitignore b/sqflite/tripartite/sqflite_common/.gitignore deleted file mode 100644 index 1d294b89b479456145a09a4ccba5814d5a235f28..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/.gitignore +++ /dev/null @@ -1,19 +0,0 @@ -.DS_Store -.packages -.pub/ -ios/.generated/ -packages -pubspec.lock - -# Directory created by dartdoc -doc/api/ - -# Local folder -.local/ - -# Conventional directory for build outputs -build/ -coverage/ - -# flutter -.metadata \ No newline at end of file diff --git a/sqflite/tripartite/sqflite_common/CHANGELOG.md b/sqflite/tripartite/sqflite_common/CHANGELOG.md deleted file mode 100644 index 25701bfbd40b485541893b56c996e695b6ff5563..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/CHANGELOG.md +++ /dev/null @@ -1,83 +0,0 @@ -# Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -## 2.4.5 - -* Add global API from sqflite (openDatabase, deleteDatabase, databaseFactory...) from sqflite - -## 2.4.4 - -* Dart 3 support - -## 2.4.3 - -* add minimum support for SQLite uri (https://www.sqlite.org/uri.html) - -## 2.4.2+2 - -* add experimental logger support. - -## 2.4.1 - -* add support for `Batch.length` to help finding the last added operation index. -* strict-casts and sdk 2.18 support - -## 2.4.0+2 - -* add support for `Database.queryCursor()` and `Database.rawQueryCursor()` -* base experimental web support -* Support for transaction v2 - -## 2.3.0 - -- Add `apply()` method to `Batch`. It will execute statements in that batch - without starting a new transaction. - -## 2.2.1+1 - -* Add debug tag to database factory - -## 2.2.0 - -* Export `Object? result` in `DatabaseException` -* Export deprecated `DatabaseFactory.debugSetLogLevel` for quick logging. - -## 2.1.0 - -* Requires dart sdk 2.15 - -## 2.0.1+1 - -* Truncate arguments in exception - -## 2.0.0+2 - -* `nnbd` support -* Fix transaction ref counting on begin transaction failure - -## 1.0.3+2 - -* Don't lock globally during open but lock per database full path. - -## 1.0.2+1 - -* Don't create a transaction during openDatabase if not needed. - -## 1.0.1 - -* Export `DatabaseException.getResultCode()`. - -## 1.0.0+1 - -* Initial revision from sqflite 1.2.2+1 diff --git a/sqflite/tripartite/sqflite_common/LICENSE b/sqflite/tripartite/sqflite_common/LICENSE deleted file mode 100644 index 5993312e79c1f45987bf413dd64b90cfff62b243..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/LICENSE +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -BSD 2-Clause License - -Copyright (c) 2019, Alexandre Roux Tekartik -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/sqflite/tripartite/sqflite_common/analysis_options.yaml b/sqflite/tripartite/sqflite_common/analysis_options.yaml deleted file mode 100644 index cdafef4e1244885f3785b1957ff0b056b628087e..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/analysis_options.yaml +++ /dev/null @@ -1,126 +0,0 @@ -# Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -include: package:lints/recommended.yaml - -# Until there are meta linter rules, each desired lint must be explicitly enabled. -# See: https://github.com/dart-lang/linter/issues/288 -# -# For a list of lints, see: http://dart-lang.github.io/linter/lints/ -# See the configuration guide for more -# https://github.com/dart-lang/sdk/tree/master/pkg/analyzer#configuring-the-analyzer -# -# NOTE: Please keep this file in sync with -# https://github.com/flutter/flutter/blob/master/analysis_options.yaml - -analyzer: - # Strong mode is sometimes harder to keep - language: - strict-casts: true - strict-inference: true - - errors: - # treat missing required parameters as a warning (not a hint) - missing_required_param: warning - # treat missing returns as a warning (not a hint) - missing_return: warning - # allow having TODOs in the code - todo: ignore - # Ignore errors like - # 'super_goes_last' is a deprecated lint rule and should not be used • included_file_warning - included_file_warning: ignore - -linter: - rules: - - always_declare_return_types - - avoid_dynamic_calls - - avoid_empty_else - - avoid_relative_lib_imports - - avoid_shadowing_type_parameters - - avoid_slow_async_io - - avoid_types_as_parameter_names - - await_only_futures - - camel_case_extensions - - camel_case_types - - cancel_subscriptions - - curly_braces_in_flow_control_structures - - depend_on_referenced_packages - - directives_ordering - - empty_catches - - hash_and_equals - - iterable_contains_unrelated_type - - library_private_types_in_public_api - - list_remove_unrelated_type - - no_adjacent_strings_in_list - - no_duplicate_case_values - - no_leading_underscores_for_library_prefixes - - no_leading_underscores_for_local_identifiers - - non_constant_identifier_names - - null_check_on_nullable_type_parameter - - omit_local_variable_types - - package_api_docs - - package_prefixed_library_names - - prefer_generic_function_type_aliases - - prefer_interpolation_to_compose_strings - - prefer_is_empty - - prefer_is_not_empty - - prefer_iterable_whereType - - prefer_single_quotes - - prefer_typing_uninitialized_variables - - sort_child_properties_last - - test_types_in_equals - - throw_in_finally - - unawaited_futures - - unnecessary_constructor_name - # - unnecessary_import - - unnecessary_late - - unnecessary_null_aware_assignments - - unnecessary_nullable_for_final_variable_declarations - - unnecessary_statements - # - unnecessary_type_check - - unrelated_type_equality_checks - - unsafe_html - - use_full_hex_values_for_flutter_colors - - valid_regexps - - - constant_identifier_names - - control_flow_in_finally - - empty_statements - - implementation_imports - - overridden_fields - - package_names - - prefer_const_constructors - - prefer_initializing_formals - - prefer_void_to_null - # - - always_require_non_null_named_parameters - - annotate_overrides - - avoid_init_to_null - - avoid_null_checks_in_equality_operators - - avoid_return_types_on_setters - - empty_constructor_bodies - - library_names - - library_prefixes - - prefer_adjacent_string_concatenation - - prefer_collection_literals - - prefer_contains - - slash_for_doc_comments - - type_init_formals - - unnecessary_const - - unnecessary_new - - unnecessary_null_in_if_null_operators - - use_rethrow_when_possible - - # === doc rules === - - public_member_api_docs diff --git a/sqflite/tripartite/sqflite_common/example/main.dart b/sqflite/tripartite/sqflite_common/example/main.dart deleted file mode 100644 index 90d5778bfcd8f82178bb06cfc601f2dc8d2641b7..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/example/main.dart +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -Future main() async { - /// This package is not intended for direct use. - /// - /// See [sqflite](https://pub.dev/packages/sqflite) -} diff --git a/sqflite/tripartite/sqflite_common/lib/sqflite.dart b/sqflite/tripartite/sqflite_common/lib/sqflite.dart deleted file mode 100644 index dd7b5efa4b18c9a0c5dca242ba603705d5da8a89..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/sqflite.dart +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'dart:async'; - -import 'package:sqflite_common/src/sqflite_database_factory.dart'; - -import 'sqlite_api.dart'; - -export 'package:sqflite_common/src/sqflite_database_factory.dart' show databaseFactory, databaseFactoryOrNull; - -export 'sqlite_api.dart'; - -/// -/// Open the database at a given path -/// -/// [version] (optional) specifies the schema version of the database being -/// opened. This is used to decide whether to call [onCreate], [onUpgrade], -/// and [onDowngrade] -/// -/// The optional callbacks are called in the following order: -/// -/// 1. [onConfigure] -/// 2. [onCreate] or [onUpgrade] or [onDowngrade] -/// 5. [onOpen] -/// -/// [onConfigure] is the first callback invoked when opening the database. It -/// allows you to perform database initialization such as enabling foreign keys -/// or write-ahead logging -/// -/// If [version] is specified, [onCreate], [onUpgrade], and [onDowngrade] can -/// be called. These functions are mutually exclusive — only one of them can be -/// called depending on the context, although they can all be specified to -/// cover multiple scenarios. If specified, it must be a 32-bits integer greater -/// than 0. -/// -/// [onCreate] is called if the database did not exist prior to calling -/// [openDatabase]. You can use the opportunity to create the required tables -/// in the database according to your schema -/// -/// [onUpgrade] is called if either of the following conditions are met: -/// -/// 1. [onCreate] is not specified -/// 2. The database already exists and [version] is higher than the last -/// database version -/// -/// In the first case where [onCreate] is not specified, [onUpgrade] is called -/// with its [oldVersion] parameter as `0`. In the second case, you can perform -/// the necessary migration procedures to handle the differing schema -/// -/// [onDowngrade] is called only when [version] is lower than the last database -/// version. This is a rare case and should only come up if a newer version of -/// your code has created a database that is then interacted with by an older -/// version of your code. You should try to avoid this scenario -/// -/// [onOpen] is the last optional callback to be invoked. It is called after -/// the database version has been set and before [openDatabase] returns -/// -/// When [readOnly] (false by default) is true, all other parameters are -/// ignored and the database is opened as-is -/// -/// When [singleInstance] is true (the default), a single database instance is -/// returned for a given path. Subsequent calls to [openDatabase] with the -/// same path will return the same instance, and will discard all other -/// parameters such as callbacks for that invocation. -/// -Future openDatabase(String path, - {int? version, - OnDatabaseConfigureFn? onConfigure, - OnDatabaseCreateFn? onCreate, - OnDatabaseVersionChangeFn? onUpgrade, - OnDatabaseVersionChangeFn? onDowngrade, - OnDatabaseOpenFn? onOpen, - bool? readOnly = false, - bool? singleInstance = true}) { - print("步骤1:${StackTrace.current.toString()}"); - final options = OpenDatabaseOptions( - version: version, - onConfigure: onConfigure, - onCreate: onCreate, - onUpgrade: onUpgrade, - onDowngrade: onDowngrade, - onOpen: onOpen, - readOnly: readOnly, - singleInstance: singleInstance); - return databaseFactory.openDatabase(path, options: options); -} - -/// -/// Open the database at a given path in read only mode -/// -Future openReadOnlyDatabase(String path, {bool? singleInstance = true}) => - openDatabase(path, readOnly: true, singleInstance: singleInstance); - -/// -/// Get the default databases location. -/// -/// On Android, it is typically data/data//databases -/// -/// On iOS and MacOS, it is the Documents directory. -/// -/// Note for iOS and non-Android platforms: Using `path_provider` is recommended to get the -/// databases directory. The most appropriate location on iOS would be -/// the Library directory that you could get from the [`path_provider` package] -/// (https://pub.dev/documentation/path_provider/latest/path_provider/getLibraryDirectory.html). -/// -Future getDatabasesPath() => databaseFactory.getDatabasesPath(); - -/// -/// Delete the database at the given path. -/// -Future deleteDatabase(String path) => databaseFactory.deleteDatabase(path); - -/// -/// Check if a database exists at a given path. -/// -Future databaseExists(String path) => databaseFactory.databaseExists(path); diff --git a/sqflite/tripartite/sqflite_common/lib/sqflite_dev.dart b/sqflite/tripartite/sqflite_common/lib/sqflite_dev.dart deleted file mode 100644 index ba5cfb1b9c00908059fe2d2785450b1e5bcd7cd7..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/sqflite_dev.dart +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/// To be deprecated -library sqflite_common_sqflite_dev; - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/mixin/import_mixin.dart'; - -/// Dev extension -/// -/// Please prefer using SqfliteDatabaseFactoryDebug which is exported by default. -extension SqfliteDatabaseFactoryDev on DatabaseFactory { - /// Change the log level if you want to see the SQL query - /// executed natively. - /// - /// Deprecated for temp usage only - @Deprecated('Dev only') - Future setLogLevel(int logLevel) async { - await setOptions(SqfliteOptions(logLevel: logLevel)); - } - - /// Testing only. - /// - /// deprecated on purpose to remove from code. - @Deprecated('Dev only') - Future setOptions(SqfliteOptions options) async { - await (this as SqfliteInvokeHandler) - .invokeMethod(methodOptions, options.toMap()); - } -} diff --git a/sqflite/tripartite/sqflite_common/lib/sqflite_logger.dart b/sqflite/tripartite/sqflite_common/lib/sqflite_logger.dart deleted file mode 100644 index 4e3565e52580ac8ec446249ebbb3eac96241b884..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/sqflite_logger.dart +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export 'src/logger/sqflite_logger.dart' - show - SqfliteDatabaseFactoryLogger, - SqfliteDatabaseFactoryLoggerType, - SqfliteLoggerOptions, - SqfliteLoggerSqlEvent, - SqfliteLoggerDatabaseOpenEvent, - SqfliteLoggerDatabaseCloseEvent, - SqfliteLoggerDatabaseDeleteEvent, - SqfliteLoggerInvokeEvent, - SqfliteLoggerBatchEvent, - SqfliteLoggerBatchOperation, - SqfliteLoggerEvent, - SqfliteLoggerSqlCommandExecute, - SqfliteLoggerSqlCommandInsert, - SqfliteLoggerSqlCommandUpdate, - SqfliteLoggerSqlCommandDelete, - SqfliteLoggerSqlCommandQuery, - SqfliteLoggerEventExt, - DatabaseFactoryLoggerDebugExt; - -export 'src/sql_command.dart' show SqliteSqlCommandType; diff --git a/sqflite/tripartite/sqflite_common/lib/sql.dart b/sqflite/tripartite/sqflite_common/lib/sql.dart deleted file mode 100644 index c1c854dcd068f85894ae6e0d76e818a2a04917ca..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/sql.dart +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Only export: -// * [ConflictAlgorithm] -// * [escapeName] -// * [unescapeName] -export 'package:sqflite_common/src/sql_builder.dart' - show ConflictAlgorithm, escapeName, unescapeName; diff --git a/sqflite/tripartite/sqflite_common/lib/sqlite_api.dart b/sqflite/tripartite/sqflite_common/lib/sqlite_api.dart deleted file mode 100644 index 20deb45337e163f94789283924c3638106dced5e..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/sqlite_api.dart +++ /dev/null @@ -1,603 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'dart:async'; - -import 'package:sqflite_common/sql.dart' show ConflictAlgorithm; -import 'package:sqflite_common/src/database.dart'; -import 'package:sqflite_common/src/database_mixin.dart'; -import 'package:sqflite_common/src/open_options.dart' as impl; -import 'package:sqflite_common/src/transaction.dart'; - -export 'package:sqflite_common/sql.dart' show ConflictAlgorithm; -export 'package:sqflite_common/src/constant.dart' - show - inMemoryDatabasePath, - sqfliteLogLevelNone, - sqfliteLogLevelSql, - sqfliteLogLevelVerbose; -export 'package:sqflite_common/src/exception.dart' show DatabaseException; -export 'package:sqflite_common/src/sqflite_debug.dart' - show SqfliteDatabaseFactoryDebug, DatabaseFactoryLoggerDebugExt; - -/// Basic databases operations -abstract class DatabaseFactory { - /// Open a database at [path] with the given [OpenDatabaseOptions]`options` - /// - /// ``` - /// var databasesPath = await getDatabasesPath(); - /// String path = join(databasesPath, 'demo.db'); - /// Database database = await openDatabase(path, version: 1, - /// onCreate: (Database db, int version) async { - /// // When creating the db, create the table - /// await db.execute( - /// 'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)'); - /// }); - ///``` - /// Notice, `join` is a part of the [path](https://pub.dev/packages/path) package - Future openDatabase(String path, {OpenDatabaseOptions? options}); - - /// Get the default databases location path. - /// - /// When using sqfliteFactory: - /// * On Android, it is typically data/data//databases - /// * On iOS and MacOS, it is the Documents directory - /// - /// For other implementation (ffi), the location is a default location - /// that makes mainly sense for debug/testing and you'd better rely on a - /// custom strategy using package such as `path_provider`. - Future getDatabasesPath(); - - /// Set the default databases location path - Future setDatabasesPath(String path); - - /// Delete a database if it exists - Future deleteDatabase(String path); - - /// Check if a database exists - Future databaseExists(String path); -} - -/// -/// Common API for [Database] and [Transaction] to execute SQL commands -/// -abstract class DatabaseExecutor { - /// Execute an SQL query with no return value. - /// - /// ``` - /// await db.execute( - /// 'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)'); - /// ``` - Future execute(String sql, [List? arguments]); - - /// Executes a raw SQL INSERT query and returns the last inserted row ID. - /// - /// ``` - /// int id1 = await database.rawInsert( - /// 'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)'); - /// ``` - /// - /// 0 could be returned for some specific conflict algorithms if not inserted. - Future rawInsert(String sql, [List? arguments]); - - /// This method helps insert a map of [values] - /// into the specified [table] and returns the - /// id of the last inserted row. - /// - /// ``` - /// var value = { - /// 'age': 18, - /// 'name': 'value' - /// }; - /// int id = await db.insert( - /// 'table', - /// value, - /// conflictAlgorithm: ConflictAlgorithm.replace, - /// ); - /// ``` - /// - /// 0 could be returned for some specific conflict algorithms if not inserted. - Future insert(String table, Map values, - {String? nullColumnHack, ConflictAlgorithm? conflictAlgorithm}); - - /// This is a helper to query a table and return the items found. All optional - /// clauses and filters are formatted as SQL queries - /// excluding the clauses' names. - /// - /// [table] contains the table names to compile the query against. - /// - /// [distinct] when set to true ensures each row is unique. - /// - /// The [columns] list specify which columns to return. Passing null will - /// return all columns, which is discouraged. - /// - /// [where] filters which rows to return. Passing null will return all rows - /// for the given URL. '?'s are replaced with the items in the - /// [whereArgs] field. - /// - /// [groupBy] declares how to group rows. Passing null - /// will cause the rows to not be grouped. - /// - /// [having] declares which row groups to include in the cursor, - /// if row grouping is being used. Passing null will cause - /// all row groups to be included, and is required when row - /// grouping is not being used. - /// - /// [orderBy] declares how to order the rows, - /// Passing null will use the default sort order, - /// which may be unordered. - /// - /// [limit] limits the number of rows returned by the query. - /// - /// [offset] specifies the starting index. - /// - /// ``` - /// List maps = await db.query(tableTodo, - /// columns: ['columnId', 'columnDone', 'columnTitle'], - /// where: 'columnId = ?', - /// whereArgs: [id]); - /// ``` - Future>> query(String table, - {bool? distinct, - List? columns, - String? where, - List? whereArgs, - String? groupBy, - String? having, - String? orderBy, - int? limit, - int? offset}); - - /// Executes a raw SQL SELECT query and returns a list - /// of the rows that were found. - /// - /// ``` - /// List list = await database.rawQuery('SELECT * FROM Test'); - /// ``` - Future>> rawQuery(String sql, - [List? arguments]); - - /// Executes a raw SQL SELECT with a cursor. - /// - /// Returns a cursor, that must either be closed when reaching the end or - /// that must be closed manually. You have to do [QueryCursor.moveNext] to - /// navigate (forward) in the cursor. - /// - /// Since its implementation cache rows for efficiency, [bufferSize] specified the - /// number of rows to cache (100 being the default) - /// - /// ``` - /// var cursor = await database.rawQueryCursor('SELECT * FROM Test'); - /// ``` - Future rawQueryCursor(String sql, List? arguments, - {int? bufferSize}); - - /// See [DatabaseExecutor.rawQueryCursor] for details about the argument [bufferSize] - /// See [DatabaseExecutor.query] for the other arguments. - Future queryCursor(String table, - {bool? distinct, - List? columns, - String? where, - List? whereArgs, - String? groupBy, - String? having, - String? orderBy, - int? limit, - int? offset, - int? bufferSize}); - - /// Executes a raw SQL UPDATE query and returns - /// the number of changes made. - /// - /// ``` - /// int count = await database.rawUpdate( - /// 'UPDATE Test SET name = ?, value = ? WHERE name = ?', - /// ['updated name', '9876', 'some name']); - /// ``` - Future rawUpdate(String sql, [List? arguments]); - - /// Convenience method for updating rows in the database. Returns - /// the number of changes made - /// - /// Update [table] with [values], a map from column names to new column - /// values. null is a valid value that will be translated to NULL. - /// - /// [where] is the optional WHERE clause to apply when updating. - /// Passing null will update all rows. - /// - /// You may include ?s in the where clause, which will be replaced by the - /// values from [whereArgs] - /// - /// [conflictAlgorithm] (optional) specifies algorithm to use in case of a - /// conflict. See [ConflictAlgorithm] docs for more details - /// - /// ``` - /// int count = await db.update(tableTodo, todo.toMap(), - /// where: '$columnId = ?', whereArgs: [todo.id]); - /// ``` - Future update(String table, Map values, - {String? where, - List? whereArgs, - ConflictAlgorithm? conflictAlgorithm}); - - /// Executes a raw SQL DELETE query and returns the - /// number of changes made. - /// - /// ``` - /// int count = await database - /// .rawDelete('DELETE FROM Test WHERE name = ?', ['another name']); - /// ``` - Future rawDelete(String sql, [List? arguments]); - - /// Convenience method for deleting rows in the database. - /// - /// Delete from [table] - /// - /// [where] is the optional WHERE clause to apply when updating. Passing null - /// will delete all rows. - /// - /// You may include ?s in the where clause, which will be replaced by the - /// values from [whereArgs] - /// - /// Returns the number of rows affected. - /// ``` - /// int count = await db.delete(tableTodo, where: 'columnId = ?', whereArgs: [id]); - /// ``` - Future delete(String table, {String? where, List? whereArgs}); - - /// Creates a batch, used for performing multiple operation - /// in a single atomic operation. - /// - /// A batch can either be committed atomically with [Batch.commit], or non- - /// atomically by calling [Batch.apply]. For details on the two methods, see - /// their documentation. - /// In general, it is recommended to finish batches with [Batch.commit]. - /// - /// When committed with [Batch.commit], sqflite will manage a transaction to - /// execute statements in the batch. If this [batch] method has been called on - /// a [Transaction], committing the batch is deferred to when the transaction - /// completes (but [Batch.apply] or [Batch.commit] still need to be called). - Batch batch(); - - /// Get the database. - Database get database; -} - -/// Database transaction -/// to use during a transaction -abstract class Transaction implements DatabaseExecutor {} - -/// -/// Database to send sql commands, created during [openDatabase] -/// -abstract class Database implements DatabaseExecutor { - /// The path of the database - String get path; - - /// Close the database. Cannot be accessed anymore - Future close(); - - /// Calls in action must only be done using the transaction object - /// using the database will trigger a dead-lock. - /// - /// ``` - /// await database.transaction((txn) async { - /// // Ok - /// await txn.execute('CREATE TABLE Test1 (id INTEGER PRIMARY KEY)'); - /// - /// // DON'T use the database object in a transaction - /// // this will deadlock! - /// await database.execute('CREATE TABLE Test2 (id INTEGER PRIMARY KEY)'); - /// }); - Future transaction(Future Function(Transaction txn) action, - {bool? exclusive}); - - /// Tell if the database is open, returns false once close has been called - bool get isOpen; - - /// testing only - @Deprecated('Dev only') - Future devInvokeMethod(String method, [Object? arguments]); - - /// testing only - @Deprecated('Dev only') - Future devInvokeSqlMethod(String method, String sql, - [List? arguments]); -} - -/// Helpers -extension SqfliteDatabaseExecutorExt on DatabaseExecutor { - SqfliteDatabase get _db => (this as SqfliteDatabaseExecutor).db; - SqfliteTransaction? get _txn => (this as SqfliteDatabaseExecutor).txn; - - /// - /// Set the database inner version - /// Used internally for open helpers and automatic versioning - /// - Future setVersion(int version) { - _db.checkNotClosed(); - return _db.txnSetVersion(_txn, version); - } - - /// - /// Get the database inner version - /// - Future getVersion() { - _db.checkNotClosed(); - return _db.txnGetVersion(_txn); - } -} - -/// Prototype of the function called when the version has changed. -/// -/// Schema migration (adding column, adding table, adding trigger...) -/// should happen here. -typedef OnDatabaseVersionChangeFn = FutureOr Function( - Database db, int oldVersion, int newVersion); - -/// Prototype of the function called when the database is created. -/// -/// Database intialization (creating tables, views, triggers...) -/// should happen here. -typedef OnDatabaseCreateFn = FutureOr Function(Database db, int version); - -/// Prototype of the function called when the database is open. -/// -/// Post initialization should happen here. -typedef OnDatabaseOpenFn = FutureOr Function(Database db); - -/// Prototype of the function called before calling [onCreate]/[onUpdate]/[onOpen] -/// when the database is open. -/// -/// Post initialization should happen here. -typedef OnDatabaseConfigureFn = FutureOr Function(Database db); - -/// to specify during [openDatabase] for [onDowngrade] -/// Downgrading will always fail -Future onDatabaseVersionChangeError( - Database db, int oldVersion, int newVersion) async { - throw ArgumentError("can't change version from $oldVersion to $newVersion"); -} - -Future __onDatabaseDowngradeDelete( - Database db, int oldVersion, int newVersion) async { - // Implementation is hidden implemented in openDatabase._onDatabaseDowngradeDelete -} - -/// Downgrading will delete the database and open it again. -/// -/// To set in [onDowngrade] if you want to delete everything on downgrade. -final OnDatabaseVersionChangeFn onDatabaseDowngradeDelete = - __onDatabaseDowngradeDelete; - -/// -/// Options for opening the database -/// see [openDatabase] for details -/// -abstract class OpenDatabaseOptions { - /// Open the database at a given path - /// - /// [version] (optional) specifies the schema version of the database being - /// opened. This is used to decide whether to call [onCreate], [onUpgrade], - /// and [onDowngrade]. If specified, it must be a 32-bits integer greater than - /// 0. - /// - /// The optional callbacks are called in the following order: - /// - /// 1. [onConfigure] - /// 2. [onCreate] or [onUpgrade] or [onDowngrade] - /// 5. [onOpen] - /// - /// [onConfigure] is the first callback invoked when opening the database. It - /// allows you to perform database initialization such as enabling foreign keys - /// or write-ahead logging - /// - /// If [version] is specified, [onCreate], [onUpgrade], and [onDowngrade] can - /// be called. These functions are mutually exclusive — only one of them can be - /// called depending on the context, although they can all be specified to - /// cover multiple scenarios - /// - /// [onCreate] is called if the database did not exist prior to calling - /// [openDatabase]. You can use the opportunity to create the required tables - /// in the database according to your schema - /// - /// [onUpgrade] is called if either of the following conditions are met: - /// - /// 1. [onCreate] is not specified - /// 2. The database already exists and [version] is higher than the last - /// database version - /// - /// In the first case where [onCreate] is not specified, [onUpgrade] is called - /// with its [oldVersion] parameter as `0`. In the second case, you can perform - /// the necessary migration procedures to handle the differing schema - /// - /// [onDowngrade] is called only when [version] is lower than the last database - /// version. This is a rare case and should only come up if a newer version of - /// your code has created a database that is then interacted with by an older - /// version of your code. You should try to avoid this scenario - /// - /// [onOpen] is the last optional callback to be invoked. It is called after - /// the database version has been set and before [openDatabase] returns - /// - /// When [readOnly] (false by default) is true, all other parameters are - /// ignored and the database is opened as-is - /// - /// When [singleInstance] is true (the default), a single database instance is - /// returned for a given path. Subsequent calls to [openDatabase] with the - /// same path will return the same instance, and will discard all other - /// parameters such as callbacks for that invocation. You could set it to - /// false for in memory database (it is forced to false for `:memory:` path) - /// but not for uri. - /// - factory OpenDatabaseOptions( - {int? version, - OnDatabaseConfigureFn? onConfigure, - OnDatabaseCreateFn? onCreate, - OnDatabaseVersionChangeFn? onUpgrade, - OnDatabaseVersionChangeFn? onDowngrade, - OnDatabaseOpenFn? onOpen, - bool? readOnly = false, - bool? singleInstance = true}) { - return impl.SqfliteOpenDatabaseOptions( - version: version, - onConfigure: onConfigure, - onCreate: onCreate, - onUpgrade: onUpgrade, - onDowngrade: onDowngrade, - onOpen: onOpen, - readOnly: readOnly, - singleInstance: singleInstance); - } - - /// Specify the expected version. - int? version; - - /// called right after opening the database. - OnDatabaseConfigureFn? onConfigure; - - /// Called when the database is created. - OnDatabaseCreateFn? onCreate; - - /// Called when the database is upgraded. - OnDatabaseVersionChangeFn? onUpgrade; - - /// Called when the database is downgraded. - /// - /// Use [onDatabaseDowngradeDelete] for re-creating the database - OnDatabaseVersionChangeFn? onDowngrade; - - /// Called after all other callbacks have been called. - OnDatabaseOpenFn? onOpen; - - /// Open the database in read-only mode (no callback called). - late bool readOnly; - - /// The existing single-instance (hot-restart) - late bool singleInstance; -} - -/// -/// A batch is used to perform multiple operation as a single atomic unit. -/// A Batch object can be acquired by calling [Database.batch]. It provides -/// methods for adding operation. None of the operation will be -/// executed (or visible locally) until commit() is called. -/// -/// -/// ``` -/// batch = db.batch(); -/// batch.insert('Test', {'name': 'item'}); -/// batch.update('Test', {'name': 'new_item'}, where: 'name = ?', whereArgs: ['item']); -/// batch.delete('Test', where: 'name = ?', whereArgs: ['item']); -/// results = await batch.commit(); -/// ``` -abstract class Batch { - /// Commits all of the operations in this batch as a single atomic unit - /// The result is a list of the result of each operation in the same order - /// if [noResult] is true, the result list is empty (i.e. the id inserted - /// the count of item changed is not returned. - /// - /// The batch is stopped if any operation failed - /// If [continueOnError] is true, all the operations in the batch are executed - /// and the failure are ignored (i.e. the result for the given operation will - /// be a DatabaseException) - /// - /// During [Database.onCreate], [Database.onUpgrade], [Database.onDowngrade] - /// (we are already in a transaction) or if the batch was created in a - /// transaction it will only be commited when - /// the transaction is commited ([exclusive] is not used then). - /// - /// Otherwise, sqflite will start a transaction to commit this batch. In rare - /// cases where you don't need an atomic operation, or where you are manually - /// managing the transaction without using sqflite APIs, you can also use - /// [apply] to run statements in this batch without a transaction managed by - /// sqflite. - Future> commit({ - bool? exclusive, - bool? noResult, - bool? continueOnError, - }); - - /// Runs all statements in this batch non-atomically. - /// - /// Unlike [commit], which starts a transaction to commit statements in this - /// batch atomically, [apply] will simply run the statements without starting - /// a transaction internally. - /// - /// This can be useful in the rare cases where you don't need a sqflite - /// transaction, for instance because you are manually starting a transaction - /// or because you simply don't need the batch to be applied atomically. - /// - /// In general, prefer [commit] to run batches over this method. - Future> apply({bool? noResult, bool? continueOnError}); - - /// See [Database.rawInsert] - void rawInsert(String sql, [List? arguments]); - - /// See [Database.insert] - void insert(String table, Map values, - {String? nullColumnHack, ConflictAlgorithm? conflictAlgorithm}); - - /// See [Database.rawUpdate] - void rawUpdate(String sql, [List? arguments]); - - /// See [Database.update] - void update(String table, Map values, - {String? where, - List? whereArgs, - ConflictAlgorithm? conflictAlgorithm}); - - /// See [Database.rawDelete] - void rawDelete(String sql, [List? arguments]); - - /// See [Database.delete] - void delete(String table, {String? where, List? whereArgs}); - - /// See [Database.execute]; - void execute(String sql, [List? arguments]); - - /// See [Database.query]; - void query(String table, - {bool? distinct, - List? columns, - String? where, - List? whereArgs, - String? groupBy, - String? having, - String? orderBy, - int? limit, - int? offset}); - - /// See [Database.query]; - void rawQuery(String sql, [List? arguments]); - - /// Current batch size - int get length; -} - -/// Cursor for query by page cursor. -abstract class QueryCursor { - /// Move to the next row. - /// - /// If false is returned, the cursor is closed and is no longer valid. - Future moveNext(); - - /// Current row data. - Map get current; - - /// Close the current cursor. - /// - /// Not needed when reaching the end of the cursor (moveNext returning false. - Future close(); -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/arg_utils.dart b/sqflite/tripartite/sqflite_common/lib/src/arg_utils.dart deleted file mode 100644 index 6614d21c903eb9d18a384388ab53d4ae4f22775c..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/arg_utils.dart +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'dart:typed_data'; - -String? _argumentToStringTruncate(Object? argument) { - if (argument == null) { - return null; - } - var text = argument.toString(); - if (text.length > 50) { - return '${text.substring(0, 50)}...'; - } - return text; -} - -/// Convert an sql argument to a printable string, truncating if necessary -String? argumentToString(Object? argument) { - if (argument is Uint8List) { - return 'Blob(${argument.length})'; - } - return _argumentToStringTruncate(argument); -} - -/// Convert sql arguments to a printable string, truncating if necessary -String argumentsToString(List arguments) => - '[${arguments.map((e) => argumentToString(e)).join(', ')}]'; - -/// Sql command and arguments formatted for logs -String sqlArgumentsToString(String sql, List? arguments) { - return '$sql${(arguments?.isNotEmpty ?? false) ? ' ${argumentsToString(arguments!)}' : ''}'; -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/batch.dart b/sqflite/tripartite/sqflite_common/lib/src/batch.dart deleted file mode 100644 index 98de7609a402cc35d82d7c0340bc3cae3f2dabbc..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/batch.dart +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/constant.dart'; -import 'package:sqflite_common/src/database.dart'; -import 'package:sqflite_common/src/sql_builder.dart'; -import 'package:sqflite_common/src/sql_command.dart'; -import 'package:sqflite_common/src/transaction.dart'; -import 'package:sqflite_common/src/utils.dart'; - -/// Batch mixin. -mixin SqfliteBatchMixin implements Batch { - @override - void insert(String table, Map values, - {String? nullColumnHack, ConflictAlgorithm? conflictAlgorithm}) { - final builder = SqlBuilder.insert(table, values, - nullColumnHack: nullColumnHack, conflictAlgorithm: conflictAlgorithm); - return rawInsert(builder.sql, builder.arguments); - } - - @override - void query(String table, - {bool? distinct, - List? columns, - String? where, - List? whereArgs, - String? groupBy, - String? having, - String? orderBy, - int? limit, - int? offset}) { - final builder = SqlBuilder.query(table, - distinct: distinct, - columns: columns, - where: where, - whereArgs: whereArgs, - groupBy: groupBy, - having: having, - orderBy: orderBy, - limit: limit, - offset: offset); - return rawQuery(builder.sql, builder.arguments); - } - - @override - void update(String table, Map values, - {String? where, - List? whereArgs, - ConflictAlgorithm? conflictAlgorithm}) { - final builder = SqlBuilder.update(table, values, - where: where, - whereArgs: whereArgs, - conflictAlgorithm: conflictAlgorithm); - return rawUpdate(builder.sql, builder.arguments); - } - - @override - void delete(String table, {String? where, List? whereArgs}) { - final builder = - SqlBuilder.delete(table, where: where, whereArgs: whereArgs); - return rawDelete(builder.sql, builder.arguments); - } -} - -/// Internal batch operation. -class SqfliteBatchOperation extends SqfliteSqlCommand { - /// Protocol method for each operation. - final String method; - - Map _getOperationParam() { - var map = { - paramMethod: method, - paramSql: sql, - if (arguments != null) paramSqlArguments: arguments - }; - // Handle in transaction change if needed - if (type == SqliteSqlCommandType.execute) { - // Check for begin/end transaction - final inTransaction = getSqlInTransactionArgument(sql); - if (inTransaction != null) { - map[paramInTransaction] = inTransaction; - } - } - return map; - } - - /// Internal batch operation. - SqfliteBatchOperation(super.type, this.method, super.sql, super.arguments); -} - -/// Batch implementation -abstract class SqfliteBatch with SqfliteBatchMixin implements Batch { - /// Get the list of operation as parameter for batch. - List> getOperationsParam() => - operations.map((e) => e._getOperationParam()).toList(); - - /// List of operations - final operations = []; - - @override - void rawInsert(String sql, [List? arguments]) { - operations.add(SqfliteBatchOperation( - SqliteSqlCommandType.insert, methodInsert, sql, arguments)); - } - - @override - void rawQuery(String sql, [List? arguments]) { - operations.add(SqfliteBatchOperation( - SqliteSqlCommandType.query, methodQuery, sql, arguments)); - } - - @override - void rawUpdate(String sql, [List? arguments]) { - operations.add(SqfliteBatchOperation( - SqliteSqlCommandType.update, methodUpdate, sql, arguments)); - } - - @override - void rawDelete(String sql, [List? arguments]) { - operations.add(SqfliteBatchOperation( - SqliteSqlCommandType.delete, methodUpdate, sql, arguments)); - } - - @override - void execute(String sql, [List? arguments]) { - operations.add(SqfliteBatchOperation( - SqliteSqlCommandType.execute, methodExecute, sql, arguments)); - } - - /// Batch size - @override - int get length => operations.length; -} - -/// Batch on a given database -class SqfliteDatabaseBatch extends SqfliteBatch { - /// Create a batch in a database - SqfliteDatabaseBatch(this.database); - - /// Our database - final SqfliteDatabase database; - - @override - Future> commit({ - bool? exclusive, - bool? noResult, - bool? continueOnError, - }) { - database.checkNotClosed(); - - return database.transaction>((Transaction txn) { - final sqfliteTransaction = txn as SqfliteTransaction; - return database.txnApplyBatch(sqfliteTransaction, this, - noResult: noResult, continueOnError: continueOnError); - }, exclusive: exclusive); - } - - @override - Future> apply({bool? noResult, bool? continueOnError}) { - return database.txnApplyBatch(null, this, - noResult: noResult, continueOnError: continueOnError); - } -} - -/// Batch on a given transaction -class SqfliteTransactionBatch extends SqfliteBatch { - /// Create a batch in a transaction - SqfliteTransactionBatch(this.transaction); - - /// Our transaction - final SqfliteTransaction transaction; - - @override - Future> commit({ - bool? exclusive, - bool? noResult, - bool? continueOnError, - }) { - if (exclusive != null) { - throw ArgumentError.value(exclusive, 'exclusive', - 'must not be set when commiting a batch in a transaction'); - } - - return apply(noResult: noResult, continueOnError: continueOnError); - } - - @override - Future> apply({bool? noResult, bool? continueOnError}) { - return transaction.database.txnApplyBatch(transaction, this, - noResult: noResult, continueOnError: continueOnError); - } -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/collection_utils.dart b/sqflite/tripartite/sqflite_common/lib/src/collection_utils.dart deleted file mode 100644 index b707b462339956e9cdb856bddbaa00a0f6cf98eb..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/collection_utils.dart +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'dart:collection'; - -import 'package:sqflite_common/src/constant.dart'; -import 'package:sqflite_common/src/constant.dart' as constant; -import 'package:sqflite_common/src/exception.dart'; - -export 'dart:async'; - -/// Native result wrapper -class Rows extends PluginList> { - /// Wrap the native list as a raw - Rows.from(List list) : super.from(list); - - @override - Map operator [](int index) { - final item = rawList[index] as Map; - return item.cast(); - } -} - -/// Unpack the native results -QueryResultSet queryResultSetFromMap(Map queryResultSetMap) { - final columns = queryResultSetMap['columns'] as List?; - final rows = queryResultSetMap['rows'] as List?; - return QueryResultSet(columns, rows); -} - -/// Native exception wrapper -DatabaseException databaseExceptionFromOperationError( - Map errorMap) { - final message = errorMap[paramErrorMessage] as String?; - return SqfliteDatabaseException(message, errorMap[paramErrorData], - resultCode: errorMap[paramErrorResultCode] as int?); -} - -/// A batch operation result is either -/// {'result':...} -/// or -/// {'error':...} -dynamic fromRawOperationResult(Map rawOperationResultMap) { - final errorMap = - rawOperationResultMap[constant.paramError] as Map?; - if (errorMap != null) { - return databaseExceptionFromOperationError(errorMap); - } - final dynamic successResult = rawOperationResultMap[constant.paramResult]; - if (successResult is Map) { - return queryResultToList(successResult); - } else if (successResult is List) { - return queryResultToList(successResult); - } - - // This could be just an int (insert) - return successResult; -} - -/// Native result to a map list as expected by the sqflite API -List> queryResultToList(dynamic queryResult) { - if (queryResult is Map) { - return queryResultSetFromMap(queryResult); - } - // dart1 - // dart2 support <= 0.7.0 - this is a list - // to remove once done on iOS and Android - if (queryResult is List) { - final rows = Rows.from(queryResult); - return rows; - } - - throw UnsupportedError('Unsupported queryResult type $queryResult'); -} - -/// Native result to a map list as expected by the sqflite API -int? queryResultCursorId(dynamic queryResult) { - if (queryResult is Map) { - return queryResult[paramCursorId] as int?; - } - throw UnsupportedError('Unsupported queryResult type $queryResult'); -} - -/// Query native result -class QueryResultSet extends ListBase> { - /// Creates a result set from a native column/row values - QueryResultSet(List? rawColumns, List? rawRows) { - _columns = rawColumns?.cast(); - _rows = rawRows?.cast>(); - - if (_columns != null) { - _columnIndexMap = {}; - - for (var i = 0; i < _columns!.length; i++) { - _columnIndexMap[_columns![i]] = i; - } - } - } - - List>? _rows; - List? _columns; - List? _keys; - late Map _columnIndexMap; - - @override - int get length => _rows?.length ?? 0; - - @override - Map operator [](int index) { - return QueryRow(this, _rows![index]); - } - - @override - void operator []=(int index, Map value) { - throw UnsupportedError('read-only'); - } - - @override - set length(int newLength) { - throw UnsupportedError('read-only'); - } - - /// Get the column index for a give column name - int? columnIndex(String? name) { - return _columnIndexMap[name!]; - } - - /// Remove duplicated - List get keys => _keys ??= _columns!.toSet().toList(growable: false); -} - -/// Query Row wrapper -class QueryRow extends MapBase { - /// Create a row from a result set information and a list of values - QueryRow(this.queryResultSet, this.row); - - /// Our result set - final QueryResultSet queryResultSet; - - /// Our row values - final List row; - - @override - dynamic operator [](Object? key) { - final stringKey = key as String?; - final columnIndex = queryResultSet.columnIndex(stringKey); - if (columnIndex != null) { - return row[columnIndex]; - } - return null; - } - - @override - void operator []=(String key, dynamic value) { - throw UnsupportedError('read-only'); - } - - @override - void clear() { - throw UnsupportedError('read-only'); - } - - @override - Iterable get keys => queryResultSet.keys; - - @override - dynamic remove(Object? key) { - throw UnsupportedError('read-only'); - } -} - -/// Single batch operation results. -class BatchResult { - /// Wrap a batch operation result. - BatchResult(this.result); - - /// Our operation result - final dynamic result; -} - -/// Batch results. -class BatchResults extends PluginList { - /// Creates a batch result from a native list. - BatchResults.from(List list) : super.from(list); - - @override - dynamic operator [](int index) { - // New in 0.13 - // It is always a Map and can be either a result or an error - final rawMap = _list[index] as Map; - return fromRawOperationResult(rawMap); - } -} - -/// Helper to handle a native list. -abstract class PluginList extends ListBase { - /// Creates a types list from a native list. - PluginList.from(List list) : _list = list; - - final List _list; - - /// Our raw native list. - List get rawList => _list; - - /// Get a raw element. - dynamic rawElementAt(int index) => _list[index]; - - @override - int get length => _list.length; - - @override - set length(int newLength) { - throw UnsupportedError('read-only'); - } - - @override - void operator []=(int index, T value) { - throw UnsupportedError('read-only'); - } -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/compat.dart b/sqflite/tripartite/sqflite_common/lib/src/compat.dart deleted file mode 100644 index 29628c0d8d8a0f53466eff9de26d1ee4d667138f..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/compat.dart +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'factory_mixin.dart'; - -/// -/// internal options. -/// -/// Used internally. -/// -/// deprecated since 1.1.1 -/// -@Deprecated('Dev only') -class SqfliteOptions { - /// deprecated - SqfliteOptions({this.logLevel}); - - // true =<0.7.0 - /// deprecated - @Deprecated('remove usage') - bool? queryAsMapList; - - /// deprecated - int? androidThreadPriority; - - /// deprecated - int? androidThreadCount; - - /// deprecated - int? logLevel; - - /// deprecated - Map toMap() { - final map = {}; - if (queryAsMapList != null) { - map['queryAsMapList'] = queryAsMapList; - } - if (androidThreadPriority != null) { - map['androidThreadPriority'] = androidThreadPriority; - } - if (androidThreadCount != null) { - map['androidThreadCount'] = androidThreadCount; - } - if (logLevel != null) { - map[paramLogLevel] = logLevel; - } - return map; - } - - /// deprecated - void fromMap(Map map) { - final dynamic queryAsMapList = map['queryAsMapList']; - if (queryAsMapList is bool) { - this.queryAsMapList = queryAsMapList; - } - final dynamic androidThreadPriority = map['androidThreadPriority']; - if (androidThreadPriority is int) { - this.androidThreadPriority = androidThreadPriority; - } - final dynamic androidThreadCount = map['androidThreadCount']; - if (androidThreadCount is int) { - this.androidThreadCount = androidThreadCount; - } - final dynamic logLevel = map[paramLogLevel]; - if (logLevel is int) { - this.logLevel = logLevel; - } - } -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/constant.dart b/sqflite/tripartite/sqflite_common/lib/src/constant.dart deleted file mode 100644 index 40abe66955b64abf03c339e5fb1a6b328f7fab0d..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/constant.dart +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// Native methods to use -// - -/// Native sql INSERT. -const String methodInsert = 'insert'; - -/// Native batch. -const String methodBatch = 'batch'; - -/// Native debug method. -const String methodDebug = 'debug'; - -/// Native options method. -const String methodOptions = 'options'; - -/// Native close database method. -const String methodCloseDatabase = 'closeDatabase'; - -/// Native open database method. -const String methodOpenDatabase = 'openDatabase'; - -/// Native sql execute. -const String methodExecute = 'execute'; - -/// Native sql UPDATE or DELETE method. -const String methodUpdate = 'update'; - -/// Native sql SELECT method. -const String methodQuery = 'query'; - -/// Native sql SELECT method. -const String methodQueryCursorNext = 'queryCursorNext'; - -/// deprecated. -const String methodGetPlatformVersion = 'getPlatformVersion'; - -/// Native getDatabasePath method. -const String methodGetDatabasesPath = 'getDatabasesPath'; - -/// Native database exists method. -const String methodDatabaseExists = 'databaseExists'; - -/// Native database delete method. -const String methodDeleteDatabase = 'deleteDatabase'; - -/// Native batch operations parameter. -const String paramOperations = 'operations'; - -/// Native batch 'no result' flag. -/// -/// if true the result of each batch operation is not filled -const String paramNoResult = 'noResult'; - -/// Native batch 'continue on error' flag. -/// -/// if true all the operation in the batch are executed even if on failed. -const String paramContinueOnError = 'continueOnError'; - -/// Batch operation method (insert/execute/query/update -const String paramMethod = 'method'; - -/// Batch operation result. -const String paramResult = 'result'; - -/// Error. -const String paramError = 'error'; - -/// Error code. -const String paramErrorCode = 'code'; - -/// Error message. -const String paramErrorMessage = 'message'; - -/// Error message. -const String paramErrorResultCode = 'resultCode'; - -/// Error data. -const String paramErrorData = 'data'; - -/// Open database 'recovered' flag. -/// -/// True if a single instance was recovered from the native world. -const String paramRecovered = 'recovered'; - -/// Open database 'recovered in transaction' flag. -/// -/// True if a single instance was recovered from the native world -/// while in a transaction. -const String paramRecoveredInTransaction = 'recoveredInTransaction'; - -/// The database path (string). -const String paramPath = 'path'; - -/// The database version (int). -const String paramVersion = 'version'; - -/// The database id (int) -const String paramId = 'id'; - -/// True if the database is in a transaction -const String paramInTransaction = 'inTransaction'; - -/// For beginTransaction, set it to null -/// Returned by beingTransaction for new implementation -/// -/// Transaction param, to set in all calls during a transaction. -/// -/// To set to null when beginning a transaction, it tells the implementation -/// that transactionId is supported by the client (compared to a raw BEGIN calls) -const String paramTransactionId = 'transactionId'; - -/// Special transaction id to force even if a transaction is running. -const int paramTransactionIdValueForce = -1; - -/// True when opening the database (bool) -const String paramReadOnly = 'readOnly'; - -/// True if opened as a single instance (bool) -const String paramSingleInstance = 'singleInstance'; - -/// SQL query (insert/execute/update/select). -/// -/// String. -const String paramSql = 'sql'; - -/// SQL query parameters. -/// -/// List. -const String paramSqlArguments = 'arguments'; - -/// SQL query cursorId parameter. -/// -/// Integer. -const String paramCursorId = 'cursorId'; - -/// SQL query cursor page size parameter. -/// -/// If null to cursor is used -/// -/// Integer. -const String paramCursorPageSize = 'cursorPageSize'; - -/// SQL query cursor next cancel parameter. -/// -/// true or false -/// -/// boolean. -const String paramCursorCancel = 'cancel'; - -/// SQLite error code -const String sqliteErrorCode = 'sqlite_error'; - -/// Special database name opened in memory -const String inMemoryDatabasePath = ':memory:'; - -/// Default duration before printing a lock warning if a database call hangs. -/// -/// Non final for changing it during testing. -/// -/// If a database called is delayed by this duration, a print will happen. -const Duration lockWarningDurationDefault = Duration(seconds: 10); - -// -// Log levels -// -/// No logs -final sqfliteLogLevelNone = 0; - -/// Log native sql commands -final sqfliteLogLevelSql = 1; - -/// Log native verbose -final sqfliteLogLevelVerbose = 2; - -// deprecated since 1.1.6 -// @deprecated -/// deprecated -const String methodSetDebugModeOn = 'debugMode'; - -/// Default buffer size for queryCursor -const int queryCursorBufferSizeDefault = 100; diff --git a/sqflite/tripartite/sqflite_common/lib/src/cursor.dart b/sqflite/tripartite/sqflite_common/lib/src/cursor.dart deleted file mode 100644 index df0fc39fe97336ce805ca39b189790b6450afba7..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/cursor.dart +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/database.dart'; -import 'package:sqflite_common/src/transaction.dart'; - -/// Sqflite query cursor wrapper. -class SqfliteQueryCursor implements QueryCursor { - final SqfliteDatabase _database; - - /// Current transaction if any - final SqfliteTransaction? txn; // transaction if any - - /// True when closed. moveNext should fail but current row remains ok - var closed = false; - - /// The native cursor id, null if not supported or if closed - int? cursorId; - - /// The current result list - List> resultList; - - /// The current index - int currentIndex = -1; - - /// Sqflite query cursor wrapper. - SqfliteQueryCursor(this._database, this.txn, this.cursorId, this.resultList); - - @override - Map get current => - _database.txnQueryCursorGetCurrent(txn, this); - - @override - Future moveNext() => _database.txnQueryCursorMoveNext(txn, this); - - @override - Future close() => _database.txnQueryCursorClose(txn, this); -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/database.dart b/sqflite/tripartite/sqflite_common/lib/src/database.dart deleted file mode 100644 index 7e89c808a015aea79df8675e4901fb5ddad2ba25..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/database.dart +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/batch.dart'; -import 'package:sqflite_common/src/factory.dart'; -import 'package:sqflite_common/src/transaction.dart'; - -import 'cursor.dart'; - -/// Base database executor. -abstract class SqfliteDatabaseExecutor implements DatabaseExecutor { - /// Executor transaction if any. - SqfliteTransaction? get txn; - - /// Executor database. - SqfliteDatabase get db; -} - -/// Open helper. -class SqfliteDatabaseOpenHelper { - /// Creates a database helper. - SqfliteDatabaseOpenHelper(this.factory, this.path, this.options); - - /// Our database factory - final SqfliteDatabaseFactory factory; - - /// Open options - final OpenDatabaseOptions? options; - - /// Our database pathy - final String path; - - /// The database once opened. - SqfliteDatabase? sqfliteDatabase; - - /// Creates a new database object. - SqfliteDatabase newDatabase(String path) => factory.newDatabase(this, path); - - /// True if the database is opened - bool get isOpen => sqfliteDatabase != null; - - // Future get databaseReady => _completer.future; - - /// Open or return the one opened. - Future openDatabase() async { - if (!isOpen) { - final database = newDatabase(path); - await database.doOpen(options!); - sqfliteDatabase = database; - } - return sqfliteDatabase!; - } - - /// Open the database if opened. - Future closeDatabase(SqfliteDatabase sqfliteDatabase) async { - if (!isOpen) { - return; - } - await sqfliteDatabase.doClose(); - this.sqfliteDatabase = null; - } -} - -/// Internal database interface. -abstract class SqfliteDatabase extends SqfliteDatabaseExecutor - implements Database { - /// Actually open the database. - Future doOpen(OpenDatabaseOptions options); - - /// Actually close the database. - Future doClose(); - - /// Database internal id. - int? id; - - /// Open options. - OpenDatabaseOptions? options; - - /// Begin a transaction. - Future beginTransaction({bool? exclusive}); - - /// Ends a transaction. - Future endTransaction(SqfliteTransaction txn); - - /// Commit a batch. - Future> txnApplyBatch( - SqfliteTransaction? txn, SqfliteBatch batch, - {bool? noResult, bool? continueOnError}); - - /// Execute a command. - Future txnExecute( - SqfliteTransaction? txn, String sql, List? arguments, - {bool? beginTransaction}); - - /// Execute a raw INSERT command. - Future txnRawInsert( - SqfliteTransaction? txn, String sql, List? arguments); - - /// Execute a raw SELECT command. - Future>> txnRawQuery( - SqfliteTransaction? txn, String sql, List? arguments); - - /// Execute a raw SELECT command by page. - Future txnRawQueryCursor(SqfliteTransaction? txn, - String sql, List? arguments, int pageSize); - - /// Cursor move next. - Future txnQueryCursorMoveNext( - SqfliteTransaction? txn, SqfliteQueryCursor cursor); - - /// Cursor current row. - Map txnQueryCursorGetCurrent( - SqfliteTransaction? txn, SqfliteQueryCursor cursor); - - /// Close the cursor. - Future txnQueryCursorClose( - SqfliteTransaction? txn, SqfliteQueryCursor cursor); - - /// Execute a raw UPDATE command. - Future txnRawUpdate( - SqfliteTransaction? txn, String sql, List? arguments); - - /// Execute a raw DELETE command. - Future txnRawDelete( - SqfliteTransaction? txn, String sql, List? arguments); - - /// Check if a database is not closed. - /// - /// Throw an exception if closed. - void checkNotClosed(); - - /// Allow database overriding. - Future invokeMethod(String method, [Object? arguments]); -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/database_mixin.dart b/sqflite/tripartite/sqflite_common/lib/src/database_mixin.dart deleted file mode 100644 index debadde0f305f521bfc25c55e11e5b9d5146478f..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/database_mixin.dart +++ /dev/null @@ -1,942 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/batch.dart'; -import 'package:sqflite_common/src/collection_utils.dart'; -import 'package:sqflite_common/src/constant.dart'; -import 'package:sqflite_common/src/cursor.dart'; -import 'package:sqflite_common/src/database.dart'; -import 'package:sqflite_common/src/exception.dart'; -import 'package:sqflite_common/src/factory.dart'; -import 'package:sqflite_common/src/path_utils.dart'; -import 'package:sqflite_common/src/sql_builder.dart'; -import 'package:sqflite_common/src/transaction.dart'; -import 'package:sqflite_common/src/utils.dart'; -import 'package:sqflite_common/src/utils.dart' as utils; -import 'package:sqflite_common/src/value_utils.dart'; -import 'package:sqflite_common/utils/utils.dart'; -import 'package:synchronized/synchronized.dart'; - -/// Base database implementation -class SqfliteDatabaseBase with SqfliteDatabaseMixin, SqfliteDatabaseExecutorMixin { - /// ctor - SqfliteDatabaseBase(SqfliteDatabaseOpenHelper openHelper, String path, {OpenDatabaseOptions? options}) { - this.openHelper = openHelper; - this.path = path; - } -} - -/// Common database/transaction implementation -mixin SqfliteDatabaseExecutorMixin implements SqfliteDatabaseExecutor { - @override - SqfliteTransaction? get txn; - - @override - SqfliteDatabase get db; - - /// Execute an SQL query with no return value - @override - Future execute(String sql, [List? arguments]) { - db.checkNotClosed(); - return db.txnExecute(txn, sql, arguments); - } - - /// Execute a raw SQL INSERT query - /// - /// Returns the last inserted record id - @override - Future rawInsert(String sql, [List? arguments]) { - db.checkNotClosed(); - return db.txnRawInsert(txn, sql, arguments); - } - - /// Insert a row into a table, where the keys of [values] correspond to - /// column names - @override - Future insert(String table, Map values, {String? nullColumnHack, ConflictAlgorithm? conflictAlgorithm}) { - final builder = SqlBuilder.insert(table, values, nullColumnHack: nullColumnHack, conflictAlgorithm: conflictAlgorithm); - return rawInsert(builder.sql, builder.arguments); - } - - /// Helper to query a table - /// - /// @param distinct true if you want each row to be unique, false otherwise. - /// @param table The table names to compile the query against. - /// @param columns A list of which columns to return. Passing null will - /// return all columns, which is discouraged to prevent reading - /// data from storage that isn't going to be used. - /// @param where A filter declaring which rows to return, formatted as an SQL - /// WHERE clause (excluding the WHERE itself). Passing null will - /// return all rows for the given URL. - /// @param groupBy A filter declaring how to group rows, formatted as an SQL - /// GROUP BY clause (excluding the GROUP BY itself). Passing null - /// will cause the rows to not be grouped. - /// @param having A filter declare which row groups to include in the cursor, - /// if row grouping is being used, formatted as an SQL HAVING - /// clause (excluding the HAVING itself). Passing null will cause - /// all row groups to be included, and is required when row - /// grouping is not being used. - /// @param orderBy How to order the rows, formatted as an SQL ORDER BY clause - /// (excluding the ORDER BY itself). Passing null will use the - /// default sort order, which may be unordered. - /// @param limit Limits the number of rows returned by the query, - /// @param offset starting index, - /// - /// @return the items found - /// - @override - Future>> query(String table, - {bool? distinct, - List? columns, - String? where, - List? whereArgs, - String? groupBy, - String? having, - String? orderBy, - int? limit, - int? offset}) { - final builder = SqlBuilder.query(table, - distinct: distinct, - columns: columns, - where: where, - groupBy: groupBy, - having: having, - orderBy: orderBy, - limit: limit, - offset: offset, - whereArgs: whereArgs); - return rawQuery(builder.sql, builder.arguments); - } - - /// Execute a raw SQL SELECT query - /// - /// Returns a list of rows that were found - @override - Future>> rawQuery(String sql, [List? arguments]) { - checkRawArgs(arguments); - return _rawQuery(sql, arguments); - } - - Future>> _rawQuery(String sql, [List? arguments]) { - db.checkNotClosed(); - return db.txnRawQuery(txn, sql, arguments); - } - - @override - Future queryCursor(String table, - {bool? distinct, - List? columns, - String? where, - List? whereArgs, - String? groupBy, - String? having, - String? orderBy, - int? limit, - int? offset, - int? bufferSize}) { - final builder = SqlBuilder.query(table, - distinct: distinct, - columns: columns, - where: where, - groupBy: groupBy, - having: having, - orderBy: orderBy, - limit: limit, - offset: offset, - whereArgs: whereArgs); - return _rawQueryCursor(builder.sql, builder.arguments, bufferSize); - } - - @override - Future rawQueryCursor(String sql, List? arguments, {int? bufferSize}) { - checkRawArgs(arguments); - return _rawQueryCursor(sql, arguments, bufferSize); - } - - Future _rawQueryCursor(String sql, List? arguments, int? pageSize) { - pageSize ??= queryCursorBufferSizeDefault; - db.checkNotClosed(); - return db.txnRawQueryCursor(txn, sql, arguments, pageSize); - } - - /// Execute a raw SQL UPDATE query - /// - /// Returns the number of changes made - @override - Future rawUpdate(String sql, [List? arguments]) { - checkRawArgs(arguments); - return _rawUpdate(sql, arguments); - } - - /// Execute a raw SQL UPDATE query - /// - /// Returns the number of changes made - Future _rawUpdate(String sql, [List? arguments]) { - db.checkNotClosed(); - return db.txnRawUpdate(txn, sql, arguments); - } - - /// Convenience method for updating rows in the database. - /// - /// Update [table] with [values], a map from column names to new column - /// values. null is a valid value that will be translated to NULL. - /// - /// [where] is the optional WHERE clause to apply when updating. - /// Passing null will update all rows. - /// - /// You may include ?s in the where clause, which will be replaced by the - /// values from [whereArgs] - /// - /// [conflictAlgorithm] (optional) specifies algorithm to use in case of a - /// conflict. See [ConflictResolver] docs for more details - @override - Future update(String table, Map values, - {String? where, List? whereArgs, ConflictAlgorithm? conflictAlgorithm}) { - final builder = SqlBuilder.update(table, values, where: where, whereArgs: whereArgs, conflictAlgorithm: conflictAlgorithm); - return rawUpdate(builder.sql, builder.arguments); - } - - /// Executes a raw SQL DELETE query - /// - /// Returns the number of changes made - @override - Future rawDelete(String sql, [List? arguments]) { - checkRawArgs(arguments); - return _rawDelete(sql, arguments); - } - - /// Execute a raw SQL UPDATE query - /// - /// Returns the number of changes made - Future _rawDelete(String sql, [List? arguments]) { - db.checkNotClosed(); - return db.txnRawDelete(txn, sql, arguments); - } - - /// Convenience method for deleting rows in the database. - /// - /// Delete from [table] - /// - /// [where] is the optional WHERE clause to apply when updating. Passing null - /// will update all rows. - /// - /// You may include ?s in the where clause, which will be replaced by the - /// values from [whereArgs] - /// - /// [conflictAlgorithm] (optional) specifies algorithm to use in case of a - /// conflict. See [ConflictResolver] docs for more details - /// - /// Returns the number of rows affected if a whereClause is passed in, 0 - /// otherwise. To remove all rows and get a count pass '1' as the - /// whereClause. - @override - Future delete(String table, {String? where, List? whereArgs}) { - final builder = SqlBuilder.delete(table, where: where, whereArgs: whereArgs); - return _rawDelete(builder.sql, builder.arguments); - } -} - -/// Common extension -extension SqfliteDatabaseMixinExt on SqfliteDatabase { - /// - /// Get the database inner version - /// - Future txnGetVersion(SqfliteTransaction? txn) async { - final rows = await txnRawQuery(txn, 'PRAGMA user_version', null); - return firstIntValue(rows) ?? 0; - } - - /// Set the database inner version - /// Used internally for open helpers and automatic versioning - /// - Future txnSetVersion(SqfliteTransaction? txn, int version) async { - await txnExecute(txn, 'PRAGMA user_version = $version', null); - } - - /// Base database map parameter. - Map getBaseDatabaseMethodArguments(SqfliteTransaction? txn) { - final map = { - paramId: id, - // transaction v2 - if (txn?.transactionId != null) paramTransactionId: txn?.transactionId - }; - return map; - } - - /// v1 and v2 support - /// Base database map parameter in transaction. - Map getBaseDatabaseMethodArgumentsInTransactionChange(SqfliteTransaction? txn, bool? inTransaction) { - final map = getBaseDatabaseMethodArguments(txn); - addInTransactionChangeParam(map, inTransaction); - return map; - } - - /// v1 and v2 support - /// Base database map parameter in transaction. - void addInTransactionChangeParam(Map map, bool? inTransaction) { - if (inTransaction != null) { - map[paramInTransaction] = inTransaction; - } - } - - Map _txnGetSqlMethodArguments(SqfliteTransaction? txn, String sql, List? sqlArguments) { - var methodArguments = { - paramSql: sql, - if (sqlArguments != null) paramSqlArguments: sqlArguments, - }..addAll(getBaseDatabaseMethodArguments(txn)); - return methodArguments; - } - - SqfliteDatabaseMixin get _mixin => this as SqfliteDatabaseMixin; - - /// try if open in read-only mode. - bool get readOnly => _mixin.openHelper?.options?.readOnly ?? false; - - /// for Update sql query - /// returns the update count - Future _txnRawUpdateOrDelete(SqfliteTransaction? txn, String sql, List? arguments) { - return _mixin.txnWriteSynchronized(txn, (_) async { - final result = await _mixin.safeInvokeMethod(methodUpdate, - {paramSql: sql, paramSqlArguments: arguments}..addAll(getBaseDatabaseMethodArguments(txn))); - return result ?? 0; - }); - } - - /// Run transaction. - Future _txnTransaction(Transaction? txn, Future Function(Transaction txn) action, {bool? exclusive}) async { - bool? successfull; - var transactionStarted = txn == null; - if (transactionStarted) { - txn = await beginTransaction(exclusive: exclusive); - } - T result; - try { - result = await action(txn); - successfull = true; - } finally { - if (transactionStarted) { - final sqfliteTransaction = txn as SqfliteTransaction; - sqfliteTransaction.successful = successfull; - await endTransaction(sqfliteTransaction); - } - } - return result; - } - - /// Begin a transaction. - Future txnBeginTransaction(SqfliteTransaction txn, {bool? exclusive}) async { - Object? response; - // never create transaction in read-only mode - if (readOnly != true) { - if (exclusive == true) { - response = await txnExecute(txn, 'BEGIN EXCLUSIVE', null, beginTransaction: true); - } else { - response = await txnExecute(txn, 'BEGIN IMMEDIATE', null, beginTransaction: true); - } - } - // Transaction v2 support, save the transaction id - if (response is Map) { - var transactionId = response[paramTransactionId]; - if (transactionId is int) { - txn.transactionId = transactionId; - } - } - } -} - -/// Sqflite database mixin. -mixin SqfliteDatabaseMixin implements SqfliteDatabase { - /// Invoke native method and wrap exception. - Future safeInvokeMethod(String method, [Object? arguments]) => - factory.wrapDatabaseException(() => invokeMethod(method, arguments)); - - /// Invoke the native method of the factory. - @override - Future invokeMethod(String method, [Object? arguments]) => _mixin.factory.invokeMethod(method, arguments); - - /// Keep our open helper for proper closing. - SqfliteDatabaseOpenHelper? openHelper; - @override - OpenDatabaseOptions? options; - - /// The factory. - SqfliteDatabaseFactory get factory => openHelper!.factory; - - @override - SqfliteDatabase get database => db; - - @override - SqfliteDatabase get db => this; - - /// True once the client called close. It should no longer invoke native - /// code - bool isClosed = false; - - @override - bool get isOpen => openHelper!.isOpen; - - @override - late String path; - - /// Special transaction created during open. - /// - /// Only not null during opening. - SqfliteTransaction? openTransaction; - - @override - SqfliteTransaction? get txn => openTransaction; - - /// Non-reentrant lock. - final Lock _rawLock = Lock(); - - // Its internal id - @override - int? id; - - /// Set when parsing BEGIN and COMMIT/ROLLBACK - bool inTransaction = false; - - /// Set internally for testing - bool doNotUseSynchronized = false; - - /// Base database map parameter. - /* - Map get getBaseDatabaseMethodArguments(txn) => - getBaseDatabaseMethodArguments(txn)(id!);*/ - - @override - Batch batch() { - return SqfliteDatabaseBatch(this); - } - - @override - void checkNotClosed() { - if (isClosed) { - throw SqfliteDatabaseException('error database_closed', null); - } - } - - @override - Future devInvokeMethod(String method, [Object? arguments]) { - return invokeMethod(method, arguments); - } - - @override - Future devInvokeSqlMethod(String method, String sql, [List? arguments]) { - return devInvokeMethod(method, {paramSql: sql, paramSqlArguments: arguments}..addAll( - // Handle the open transactin if any, but this is just for testing - getBaseDatabaseMethodArguments(txn))); - } - - /// synchronized call to the database - /// not re-entrant - /// Ugly compatibility step to not support older synchronized - /// mechanism - Future txnSynchronized(Transaction? txn, Future Function(Transaction? txn) action) async { - // If in a transaction, execute right away - if (txn != null || doNotUseSynchronized) { - return await action(txn); - } else { - // Simple timeout warning if we cannot get the lock after XX seconds - final handleTimeoutWarning = (utils.lockWarningDuration != null && utils.lockWarningCallback != null); - late Completer timeoutCompleter; - if (handleTimeoutWarning) { - timeoutCompleter = Completer(); - } - - // Grab the lock - final operation = _rawLock.synchronized(() { - if (handleTimeoutWarning) { - timeoutCompleter.complete(); - } - return action(txn); - }); - // Simply warn the developer as this could likely be a deadlock - if (handleTimeoutWarning) { - // ignore: unawaited_futures - timeoutCompleter.future.timeout(utils.lockWarningDuration!, onTimeout: () { - utils.lockWarningCallback!(); - }); - } - return await operation; - } - } - - /// synchronized call to the database - /// not re-entrant - Future txnWriteSynchronized(Transaction? txn, Future Function(Transaction? txn) action) => - txnSynchronized(txn, action); - - /// for sql without return values - /// - /// [beginTransaction] is true when beginning a transaction. - @override - Future txnExecute(SqfliteTransaction? txn, String sql, List? arguments, {bool? beginTransaction}) { - return txnWriteSynchronized(txn, (_) { - var inTransactionChange = getSqlInTransactionArgument(sql); - - if (inTransactionChange ?? false) { - inTransactionChange = true; - inTransaction = true; - } else if (inTransactionChange == false) { - inTransactionChange = false; - inTransaction = false; - } - return invokeExecute(txn, sql, arguments, inTransactionChange: inTransactionChange, beginTransaction: beginTransaction); - }); - } - - /// [inTransactionChange] is true when entering a transaction, false when leaving - /// should be set by parsing the sql command for all commands - /// - /// [beginTransaction] is true when entering a transaction and should clear - /// the transaction param. - Future invokeExecute(SqfliteTransaction? txn, String sql, List? arguments, - {bool? inTransactionChange, bool? beginTransaction}) { - var methodArguments = _txnGetSqlMethodArguments(txn, sql, arguments); - // Transaction v2, tell our support for transaction id - if (beginTransaction == true) { - methodArguments[paramTransactionId] = null; - } - addInTransactionChangeParam(methodArguments, inTransactionChange); - return safeInvokeMethod(methodExecute, methodArguments); - } - - /// for INSERT sql query - /// returns the last inserted record id - /// - /// 0 returned instead of null - @override - Future txnRawInsert(SqfliteTransaction? txn, String sql, List? arguments) { - return txnWriteSynchronized(txn, (_) async { - // The value could be null (for insert ignore). Return 0 in this case - return await safeInvokeMethod(methodInsert, _txnGetSqlMethodArguments(txn, sql, arguments)) ?? 0; - }); - } - - @override - Future>> txnRawQuery(SqfliteTransaction? txn, String sql, List? arguments) { - return txnSynchronized(txn, (_) async { - final dynamic result = await safeInvokeMethod(methodQuery, _txnGetSqlMethodArguments(txn, sql, arguments)); - return queryResultToList(result); - }); - } - - @override - Future txnRawQueryCursor(SqfliteTransaction? txn, String sql, List? arguments, int pageSize) { - return txnSynchronized(txn, (_) async { - var methodArguments = _txnGetSqlMethodArguments(txn, sql, arguments); - methodArguments[paramCursorPageSize] = pageSize; - dynamic result = await safeInvokeMethod(methodQuery, methodArguments); - - var cursorId = queryResultCursorId(result); - var resultList = queryResultToList(result); - return SqfliteQueryCursor(this, txn, cursorId, resultList); - }); - } - - /// Cursor current row. - @override - Map txnQueryCursorGetCurrent(SqfliteTransaction? txn, SqfliteQueryCursor cursor) { - if (cursor.closed) { - throw StateError('Cursor is closed, cannot get current row'); - } - if (cursor.currentIndex < 0 || cursor.currentIndex >= cursor.resultList.length) { - throw StateError('You must have a successful moveNext() before getting the current row'); - } - return cursor.resultList[cursor.currentIndex]; - } - - Future _closeCursor(SqfliteQueryCursor cursor) async { - if (!cursor.closed) { - cursor.closed = true; - var cursorId = cursor.cursorId; - if (cursorId != null) { - cursor.cursorId = null; - await safeInvokeMethod(methodQueryCursorNext, - {paramCursorId: cursorId, paramCursorCancel: true}..addAll(getBaseDatabaseMethodArguments(txn))); - } - } - } - - @override - Future txnQueryCursorMoveNext(SqfliteTransaction? txn, SqfliteQueryCursor cursor) async { - if (cursor.closed) { - return false; - } - if (cursor.currentIndex < cursor.resultList.length - 1) { - cursor.currentIndex++; - return true; - } - var cursorId = cursor.cursorId; - if (cursorId == null) { - // At end, let's quit - await txnQueryCursorClose(txn, cursor); - return false; - } else { - return txnSynchronized(txn, (_) async { - if (cursor.closed) { - return false; - } - var cursorId = cursor.cursorId; - if (cursorId == null) { - // At end, let's quit - await _closeCursor(cursor); - return false; - } - // Ok let's fetch the next batch of data - var result = await safeInvokeMethod( - methodQueryCursorNext, - { - paramCursorId: cursorId, - }..addAll(getBaseDatabaseMethodArguments(txn))); - var updatedCursorId = queryResultCursorId(result); - cursor.cursorId = updatedCursorId; - cursor.currentIndex = 0; - cursor.resultList = queryResultToList(result); - if (cursor.resultList.isEmpty) { - // cursor id should be null, but who knows... - await _closeCursor(cursor); - return false; - } else { - return true; - } - }); - } - } - - @override - Future txnQueryCursorClose(SqfliteTransaction? txn, SqfliteQueryCursor cursor) async { - if (!cursor.closed) { - if (cursor.cursorId != null) { - return txnSynchronized(txn, (_) async { - await _closeCursor(cursor); - }); - } else { - cursor.closed = true; - } - } - } - - /// for Update sql query - /// returns the update count - @override - Future txnRawUpdate(SqfliteTransaction? txn, String sql, List? arguments) => - _txnRawUpdateOrDelete(txn, sql, arguments); - - /// for Delete sql query - /// returns the delete count - @override - Future txnRawDelete(SqfliteTransaction? txn, String sql, List? arguments) => - _txnRawUpdateOrDelete(txn, sql, arguments); - - @override - Future> txnApplyBatch(SqfliteTransaction? txn, SqfliteBatch batch, {bool? noResult, bool? continueOnError}) { - return txnWriteSynchronized(txn, (_) async { - final arguments = {paramOperations: batch.getOperationsParam()} - ..addAll(getBaseDatabaseMethodArguments(txn)); - if (noResult == true) { - arguments[paramNoResult] = noResult; - } - if (continueOnError == true) { - arguments[paramContinueOnError] = continueOnError; - } - final results = await safeInvokeMethod?>(methodBatch, arguments); - - // Typically when noResult is true - if (results == null) { - return []; - } - // dart2 - wrap if we need to support more results than just int - return BatchResults.from(results); - }); - } - - /// New transaction. - SqfliteTransaction newTransaction() { - final txn = SqfliteTransaction(this); - return txn; - } - - @override - Future beginTransaction({bool? exclusive}) async { - final txn = newTransaction(); - await txnBeginTransaction(txn, exclusive: exclusive); - return txn; - } - - @override - Future endTransaction(SqfliteTransaction txn) async { - // never commit transaction in read-only mode - if (readOnly != true) { - if (txn.successful == true) { - await txnExecute(txn, 'COMMIT', null); - } else { - await txnExecute(txn, 'ROLLBACK', null); - } - } - } - - @override - Future transaction(Future Function(Transaction txn) action, {bool? exclusive}) { - checkNotClosed(); - return txnWriteSynchronized(txn, (Transaction? txn) async { - return _txnTransaction(txn, action, exclusive: exclusive); - }); - } - - /// Close the database. Cannot be access anymore - @override - Future close() => factory.closeDatabase(this); - - /// Close the database. Cannot be access anymore - @override - Future doClose() => _closeDatabase(id); - - @override - String toString() { - return '$id $path'; - } - - /// Open a database and returns its id. - /// - /// id does not run any callback calls - Future openDatabase() async { - final params = {paramPath: path}; - if (readOnly == true) { - params[paramReadOnly] = true; - } - // Single instance? never for standard inMemoryDatabase - final singleInstance = (options?.singleInstance ?? false) && !isInMemoryDatabasePath(path); - - params[paramSingleInstance] = singleInstance; - - // Version up to 1.1.5 returns an int - // Now it returns some database information - // the one being about being recovered from the native world - // where we are going to revert - // doing first on Android without breaking ios - final openResult = await safeInvokeMethod(methodOpenDatabase, params); - if (openResult is int) { - return openResult; - } else if (openResult is Map) { - final id = openResult[paramId] as int?; - // Recover means we found an instance in the native world - final recoveredInTransaction = openResult[paramRecoveredInTransaction] == true; - // in this case, we are going to rollback any changes in case a transaction - // was in progress. This catches hot-restart scenario - if (recoveredInTransaction) { - // Don't do it for read-only - if (readOnly != true) { - // We are not yet open so invoke the plugin directly - try { - await safeInvokeMethod(methodExecute, { - paramSql: 'ROLLBACK', - paramId: id, - - /// Force the action even if we are in a transaction. - paramTransactionId: paramTransactionIdValueForce, - paramInTransaction: false - }); - } catch (e) { - print('ignore recovered database ROLLBACK error $e'); - } - } - } - return id!; - } else { - throw 'unsupported result $openResult (${openResult?.runtimeType})'; - } - } - - final Lock _closeLock = Lock(); - - /// rollback any pending transaction if needed - Future _closeDatabase(int? databaseId) async { - await _closeLock.synchronized(() async { - // devPrint('_closeDatabase closing $databaseId inTransaction $inTransaction isClosed $isClosed readOnly $readOnly'); - if (!isClosed) { - // Mark as closed now - isClosed = true; - - if (readOnly != true && inTransaction) { - // Grab lock to prevent future access - // At least we know no other request will be ran - try { - await txnWriteSynchronized(txn, (Transaction? txn) async { - // Special trick to cancel any pending transaction - try { - await invokeExecute( - - /// Force if needed - (txn as SqfliteTransaction?) ?? getForcedSqfliteTransaction(this), - 'ROLLBACK', - null, - inTransactionChange: false); - } catch (_) { - // devPrint('rollback error $_'); - } - }); - } catch (e) { - print('Error $e before rollback'); - } - } - - // close for good - // Catch exception, close should never fail - try { - await safeInvokeMethod(methodCloseDatabase, {paramId: databaseId}); - } catch (e) { - print('error $e closing database $databaseId'); - } - } - }); - } - - // To call during open - // not exported - @override - Future doOpen(OpenDatabaseOptions options) async { - if (options.version != null) { - if (options.version == 0) { - throw ArgumentError('version cannot be set to 0 in openDatabase'); - } - } else { - if (options.onCreate != null) { - throw ArgumentError('onCreate must be null if no version is specified'); - } - if (options.onUpgrade != null) { - throw ArgumentError('onUpgrade must be null if no version is specified'); - } - if (options.onDowngrade != null) { - throw ArgumentError('onDowngrade must be null if no version is specified'); - } - } - this.options = options; - var databaseId = await openDatabase(); - - try { - // Special on downgrade delete database - if (options.onDowngrade == onDatabaseDowngradeDelete) { - // Downgrading will delete the database and open it again - Future onDatabaseDowngradeDoDelete(Database database, int oldVersion, int newVersion) async { - final db = database as SqfliteDatabase; - // This is tricky as we are in the middle of opening a database - // need to close what is being done and restart - await db.doClose(); - // But don't mark it as closed - isClosed = false; - - await factory.deleteDatabase(db.path); - - // get a new database id after open - db.id = databaseId = await openDatabase(); - - try { - // Since we deleted the database re-run the needed first steps: - // onConfigure then onCreate - if (options.onConfigure != null) { - await options.onConfigure!(db); - } - } catch (e) { - // This exception is sometimes hard te catch - // during development - print(e); - - // create a transaction just to make the current transaction happy - openTransaction = await db.beginTransaction(exclusive: true); - rethrow; - } - - // Recreate a new transaction - // no end transaction it will be done later before calling then onOpen - openTransaction = await db.beginTransaction(exclusive: true); - if (options.onCreate != null) { - await options.onCreate!(db, options.version!); - } - } - - options.onDowngrade = onDatabaseDowngradeDoDelete; - } - - id = databaseId; - - // first configure it - if (options.onConfigure != null) { - await options.onConfigure!(this); - } - - if (options.version != null) { - // Check the version outside of the transaction - // And only create the transaction if needed (https://github.com/tekartik/sqflite/issues/459) - final oldVersion = await getVersion(); - if (oldVersion != options.version) { - try { - await transaction((Transaction txn) async { - // Set the current transaction as the open one - // to allow direct database call during open and allowing - // creating a fake transaction (since we are already in a transaction) - final sqfliteTransaction = txn as SqfliteTransaction; - openTransaction = sqfliteTransaction; - - // We read again the version to be safe regarding edge cases - final oldVersion = await txnGetVersion(txn); - if (oldVersion == 0) { - if (options.onCreate != null) { - await options.onCreate!(this, options.version!); - } else if (options.onUpgrade != null) { - await options.onUpgrade!(this, 0, options.version!); - } - } else if (options.version! > oldVersion) { - if (options.onUpgrade != null) { - await options.onUpgrade!(this, oldVersion, options.version!); - } - } else if (options.version! < oldVersion) { - if (options.onDowngrade != null) { - await options.onDowngrade!(this, oldVersion, options.version!); - // Check and reuse transaction if if needed - // in case downgrade delete was called - if (openTransaction!.transactionId != txn.transactionId) { - txn.transactionId = openTransaction!.transactionId; - } - } - } - if (oldVersion != options.version) { - await setVersion(options.version!); - } - }, exclusive: true); - } finally { - // clean up open transaction - openTransaction = null; - } - } - } - - if (options.onOpen != null) { - await options.onOpen!(this); - } - - return this; - } catch (e) { - print('error $e during open, closing...'); - await _closeDatabase(databaseId); - rethrow; - } finally { - // clean up open transaction - openTransaction = null; - } - } -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/dev_utils.dart b/sqflite/tripartite/sqflite_common/lib/src/dev_utils.dart deleted file mode 100644 index 036fc25f0cc1f542db209509314eb0bddf85f70c..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/dev_utils.dart +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/// Deprecated to prevent keeping the code used. -@Deprecated('Dev only') -void devPrint(Object? object) { - print(object); -} - -/// Deprecated to prevent keeping the code used. -/// -/// Can be use as a todo for weird code. int value = devWarning(myFunction()); -/// The function is always called -@Deprecated('Dev only') -T devWarning(T value) => value; diff --git a/sqflite/tripartite/sqflite_common/lib/src/env_utils.dart b/sqflite/tripartite/sqflite_common/lib/src/env_utils.dart deleted file mode 100644 index de2622515f184f0b18c78adcf579ad41707150b5..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/env_utils.dart +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// environment utils - -bool? _isRelease; - -// http://stackoverflow.com/questions/29592826/detect-during-runtime-whether-the-application-is-in-release-mode-or-not - -/// Check whether in release mode -bool get isRelease { - if (_isRelease == null) { - _isRelease = true; - assert(() { - _isRelease = false; - return true; - }()); - } - return _isRelease!; -} - -/// Check whether running in debug mode -bool get isDebug => !isRelease; - -/// Special runtime trick to known whether we are in the javascript world -const kSqfliteIsWeb = identical(1, 1.0); diff --git a/sqflite/tripartite/sqflite_common/lib/src/exception.dart b/sqflite/tripartite/sqflite_common/lib/src/exception.dart deleted file mode 100644 index 7b267966e41c2fec08f915126622b6c4c0797204..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/exception.dart +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/src/arg_utils.dart'; -import 'package:sqflite_common/src/constant.dart'; - -/// Wrap sqlite native exception -abstract class DatabaseException implements Exception { - /// Create an exception with a message - DatabaseException(this._message); - - final String? _message; - - @override - String toString() => 'DatabaseException($_message)'; - - /// True if the exception is a no such table exception - bool isNoSuchTableError([String? table]) { - if (_message != null) { - var expected = 'no such table: '; - if (table != null) { - expected += table; - } - return _message!.contains(expected); - } - return false; - } - - /// True if the exception is a duplicate column error - bool isDuplicateColumnError([String? column]) { - if (_message != null) { - var expected = 'duplicate column name: '; - if (column != null) { - expected += column; - } - return _message!.contains(expected); - } - return false; - } - - /// True if the exception is a syntax error - bool isSyntaxError() { - if (_message != null) { - return _message!.contains('syntax error'); - } - return false; - } - - /// True if the exception is an open failed error - bool isOpenFailedError() { - if (_message != null) { - return _message!.contains('open_failed'); - } - return false; - } - - /// True if the exception is a database closed error - bool isDatabaseClosedError() { - if (_message != null) { - return _message!.contains('database_closed') || - _message!.contains('This database has already been closed'); - } - return false; - } - - /// True if the exception is a read-only error - bool isReadOnlyError() { - if (_message != null) { - return _message!.contains('readonly'); - } - return false; - } - - /// True if the exception is a unique constraint error - bool isUniqueConstraintError([String? field]) { - if (_message != null) { - var expected = 'UNIQUE constraint failed: '; - if (field != null) { - expected += field; - } - return _message!.toLowerCase().contains(expected.toLowerCase()); - } - return false; - } - - /// True if the exception is a not null constraint error - bool isNotNullConstraintError([String? field]) { - if (_message != null) { - var expected = 'NOT NULL constraint failed: '; - if (field != null) { - expected += field; - } - return _message!.toLowerCase().contains(expected.toLowerCase()); - } - return false; - } - - /// Extended result code on Android/ffi, normal result code on iOS. - /// - /// This might involve parsing the sqlite native message to extract the code - /// See https://www.sqlite.org/rescode.html for the list of result code - int? getResultCode(); - - /// Platform specific error result. - /// - /// Its content is platform dependent and used internally and could change - /// in the future but could help in analyzing the error. - Object? get result; -} - -/// Exception implementation -class SqfliteDatabaseException extends DatabaseException { - /// ctor with a message and some data - SqfliteDatabaseException(String? message, this.result, {int? resultCode}) - : super(message) { - _resultCode = resultCode; - } - - /// Our exception message - String? get message => _message; - - /// Extended result code. - int? _resultCode; - - /// Typically the result of a native call - @override - Object? result; - - /// The result as a map - Map get resultMap => result as Map; - - @override - String toString() { - if (result is Map) { - if (resultMap[paramSql] != null) { - final dynamic args = resultMap[paramSqlArguments]; - if (args is List) { - return "DatabaseException($_message) sql '${resultMap[paramSql]}' args ${argumentsToString(args)}"; - } else { - return "DatabaseException($_message) sql '${resultMap[paramSql]}'"; - } - } - } - return super.toString(); - } - - /// Get the (extended if available) result code. - /// - /// This might involve parsing the sqlite native message to extract the code - /// See https://www.sqlite.org/rescode.html for the list of result code. - /// - /// iOS returns normal code while Android/ffi returns extended code for now - /// The application should handle both. - @override - int? getResultCode() => _resultCode ??= () { - final message = _message!.toLowerCase(); - int? findCode(String patternPrefix) { - final index = message.indexOf(patternPrefix); - if (index != -1) { - try { - // Split at first space - var code = message - .substring(index + patternPrefix.length) - .trim() - .split(' ')[0]; - // Find ending parenthesis if any - final endIndex = code.indexOf(')'); - if (endIndex != -1) { - code = code.substring(0, endIndex); - } - - final resultCode = int.tryParse(code); - if (resultCode != null) { - return resultCode; - } - } catch (_) {} - } - return null; - } - - var code = findCode('(sqlite code '); - if (code != null) { - return code; - } - code = findCode('(code '); - if (code != null) { - return code; - } - // ios - code = findCode('code='); - if (code != null) { - return code; - } - return null; - }(); -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/factory.dart b/sqflite/tripartite/sqflite_common/lib/src/factory.dart deleted file mode 100644 index b0abd28d620441d3289451d5395ac5226a3f5482..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/factory.dart +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/database.dart'; -import 'package:sqflite_common/src/mixin/factory.dart'; - -/// Internal database factory interface. -abstract class SqfliteDatabaseFactory - implements DatabaseFactory, SqfliteInvokeHandler { - /// Wrap any exception to a [DatabaseException]. - Future wrapDatabaseException(Future Function() action); - - // To override - // This also should wrap exception - //Future safeInvokeMethod(String method, [Object? arguments]); - - /// Create a new database object. - SqfliteDatabase newDatabase( - SqfliteDatabaseOpenHelper openHelper, String path); - - /// Remove our internal open helper. - void removeDatabaseOpenHelper(String path); - - @override - Future openDatabase(String path, {OpenDatabaseOptions? options}); - - /// Close the database. - /// - /// db.close() calls this right await. - Future closeDatabase(SqfliteDatabase database); - - @override - Future deleteDatabase(String path); - - @override - Future databaseExists(String path); -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/factory_mixin.dart b/sqflite/tripartite/sqflite_common/lib/src/factory_mixin.dart deleted file mode 100644 index ddc19d132f4ecbffbbee67e15f957c6c4b5fc18c..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/factory_mixin.dart +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:path/path.dart'; -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/constant.dart'; -import 'package:sqflite_common/src/database.dart'; -import 'package:sqflite_common/src/database_mixin.dart'; -import 'package:sqflite_common/src/exception.dart'; -import 'package:sqflite_common/src/factory.dart'; -import 'package:sqflite_common/src/mixin/factory.dart'; -import 'package:sqflite_common/src/open_options.dart'; -import 'package:synchronized/synchronized.dart'; -import 'path_utils.dart' as pu; - -/// Base factory implementation -abstract class SqfliteDatabaseFactoryBase with SqfliteDatabaseFactoryMixin {} - -/// Named lock, unique by name and its private class -class _NamedLock { - factory _NamedLock(String name) { - // Add to cache, create if needed - return cacheLocks[name] ??= _NamedLock._(name, Lock(reentrant: true)); - } - - _NamedLock._(this.name, this.lock); - - // Global cache per db name - // Remain allocated forever but that is fine. - static final cacheLocks = {}; - - final String name; - final Lock lock; -} - -/// Common factory mixin -mixin SqfliteDatabaseFactoryMixin implements SqfliteDatabaseFactory, SqfliteInvokeHandler { - /// To override to wrap wanted exception - @override - Future wrapDatabaseException(Future Function() action) => action(); - - /// Invoke native method and wrap exception. - Future safeInvokeMethod(String method, [Object? arguments]) => - wrapDatabaseException(() => invokeMethod(method, arguments)); - - /// Open helpers for single instances only. - Map databaseOpenHelpers = {}; - - /// Avoid concurrent open operation on the same database - Lock _getDatabaseOpenLock(String path) => _NamedLock(path).lock; - - /// Optional tag (read-only) - String? tag; - - @override - SqfliteDatabase newDatabase(SqfliteDatabaseOpenHelper openHelper, String path) { - return SqfliteDatabaseBase(openHelper, path); - } - - @override - void removeDatabaseOpenHelper(String path) { - databaseOpenHelpers.remove(path); - } - - // Close an instance of the database - @override - Future closeDatabase(SqfliteDatabase database) { - // Lock per database name - final lock = _getDatabaseOpenLock(database.path); - return lock.synchronized(() async { - await (database as SqfliteDatabaseMixin).openHelper!.closeDatabase(database); - if (database.options?.singleInstance != false) { - removeDatabaseOpenHelper(database.path); - } - }); - } - - @override - Future openDatabase(String path, {OpenDatabaseOptions? options}) async { - print("步骤2:${StackTrace.current.toString()}"); - path = await fixPath(path); - // Lock per database name - final lock = _getDatabaseOpenLock(path); - return lock.synchronized(() async { - options ??= SqfliteOpenDatabaseOptions(); - - if (options?.singleInstance != false) { - SqfliteDatabaseOpenHelper? getExistingDatabaseOpenHelper(String path) { - return databaseOpenHelpers[path]; - } - - void setDatabaseOpenHelper(SqfliteDatabaseOpenHelper? helper) { - if (helper == null) { - databaseOpenHelpers.remove(path); - } else { - databaseOpenHelpers[path] = helper; - } - } - - var databaseOpenHelper = getExistingDatabaseOpenHelper(path); - - final firstOpen = databaseOpenHelper == null; - if (firstOpen) { - databaseOpenHelper = SqfliteDatabaseOpenHelper(this, path, options); - setDatabaseOpenHelper(databaseOpenHelper); - } - try { - return await databaseOpenHelper.openDatabase(); - } catch (e) { - // If first open fail remove the reference - if (firstOpen) { - removeDatabaseOpenHelper(path); - } - rethrow; - } - } else { - final databaseOpenHelper = SqfliteDatabaseOpenHelper(this, path, options); - return await databaseOpenHelper.openDatabase(); - } - }); - } - - @override - Future deleteDatabase(String path) async { - path = await fixPath(path); - // Lock per database name - final lock = _getDatabaseOpenLock(path); - return lock.synchronized(() async { - // Handle already single instance open database - removeDatabaseOpenHelper(path); - return safeInvokeMethod(methodDeleteDatabase, {paramPath: path}); - }); - } - - @override - Future databaseExists(String path) async { - path = await fixPath(path); - return safeInvokeMethod(methodDatabaseExists, {paramPath: path}); - } - - String? _databasesPath; - - @override - Future getDatabasesPath() async { - if (_databasesPath == null) { - final path = await safeInvokeMethod(methodGetDatabasesPath); - - if (path == null) { - throw SqfliteDatabaseException('getDatabasesPath is null', null); - } - _databasesPath = path; - } - return _databasesPath!; - } - - /// Set the databases path. - @override - @Deprecated('Use setDatabasesPathOrNull') - Future setDatabasesPath(String? path) async { - setDatabasesPathOrNull(path); - } - - /// Set the databases path. - void setDatabasesPathOrNull(String? path) { - _databasesPath = path; - } - - /// True if a database path is in memory - // @Deprecated('use path_utils.isInMemoryDatabasePath') - static bool isInMemoryDatabasePath(String path) => pu.isInMemoryDatabasePath(path); - - final bool _kIsWeb = identical(0, 0.0); - - /// path must be non null - Future fixPath(String path) async { - /// Transform file::memory: to :memory as current implementation - /// relies on this feature. - if (pu.isInMemoryDatabasePath(path)) { - return inMemoryDatabasePath; - } else if (_kIsWeb || pu.isFileUriDatabasePath(path)) { - // nothing - } else { - if (isRelative(path)) { - path = join(await getDatabasesPath(), path); - } - path = absolute(normalize(path)); - } - return path; - } - - /// Debug information. - Future getDebugInfo() async { - final info = SqfliteDebugInfo(); - final map = await safeInvokeMethod(methodDebug, {'cmd': 'get'}); - final databasesMap = map[paramDatabases]; - if (databasesMap is Map) { - info.databases = databasesMap.map((dynamic id, dynamic info) { - final dbInfo = SqfliteDatabaseDebugInfo(); - final databaseId = id.toString(); - - if (info is Map) { - dbInfo.fromMap(info); - } - return MapEntry(databaseId, dbInfo); - }); - } - info.logLevel = map[paramLogLevel] as int?; - return info; - } - - @override - String toString() => 'SqfliteDatabaseFactory(${tag ?? 'sqflite'})'; -} - -// When opening the database (bool) -/// Native parameter (int) -const String paramLogLevel = 'logLevel'; - -/// Native parameter -const String paramDatabases = 'databases'; - -/// Debug information -class SqfliteDatabaseDebugInfo { - /// Database path - String? path; - - /// Whether the database was open as a single instance - bool? singleInstance; - - /// Log level - int? logLevel; - - /// Deserializer - void fromMap(Map map) { - path = map[paramPath]?.toString(); - singleInstance = map[paramSingleInstance] as bool?; - logLevel = map[paramLogLevel] as int?; - } - - /// Debug formatting helper - Map toDebugMap() { - final map = {paramPath: path, paramSingleInstance: singleInstance}; - if ((logLevel ?? sqfliteLogLevelNone) > sqfliteLogLevelNone) { - map[paramLogLevel] = logLevel; - } - return map; - } - - @override - String toString() => toDebugMap().toString(); -} - -/// Internal debug info -class SqfliteDebugInfo { - /// List of databases - Map? databases; - - /// global log level (set for new opened databases) - int? logLevel; - - /// Debug formatting helper - Map toDebugMap() { - final map = {}; - if (databases != null) { - map[paramDatabases] = databases! - .map((String key, SqfliteDatabaseDebugInfo dbInfo) => MapEntry>(key, dbInfo.toDebugMap())); - } - if ((logLevel ?? sqfliteLogLevelNone) > sqfliteLogLevelNone) { - map[paramLogLevel] = logLevel; - } - return map; - } - - @override - String toString() => toDebugMap().toString(); -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/internals.dart b/sqflite/tripartite/sqflite_common/lib/src/internals.dart deleted file mode 100644 index fd12f32a6a0eeaf5fc54d2213d25a6c18d5f7689..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/internals.dart +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:meta/meta.dart'; -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/database_mixin.dart'; -import 'package:sqflite_common/src/factory.dart'; - -/// Internal access to invoke method -extension DatabaseFactoryInternalsExt on DatabaseFactory { - /// Call invoke method manually. - @visibleForTesting - Future internalsInvokeMethod(String method, Object? arguments) async { - return (this as SqfliteDatabaseFactory).invokeMethod(method, arguments); - } -} - -/// Internal access to database configuration -extension DatabaseInternalsExt on Database { - /// Do not use synchronized to allow concurrent access - @visibleForTesting - set internalsDoNotUseSynchronized(bool doNotUseSynchronized) => - (this as SqfliteDatabaseMixin).doNotUseSynchronized = - doNotUseSynchronized; - - /// Internal database id. - @visibleForTesting - int? get databaseId => (this as SqfliteDatabaseMixin).id; -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/log_level.dart b/sqflite/tripartite/sqflite_common/lib/src/log_level.dart deleted file mode 100644 index d59c2d5499f5a90549c621c8a4fbeaf64f700c68..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/log_level.dart +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ diff --git a/sqflite/tripartite/sqflite_common/lib/src/logger/sqflite_logger.dart b/sqflite/tripartite/sqflite_common/lib/src/logger/sqflite_logger.dart deleted file mode 100644 index e4e9f9c95b62bfbcc664a7405f7e40a9e428fb5a..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/logger/sqflite_logger.dart +++ /dev/null @@ -1,895 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'dart:async'; -import 'dart:core'; -import 'dart:core' as core; -import 'package:meta/meta.dart'; -import 'package:sqflite_common/sqflite_logger.dart'; -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/batch.dart'; -import 'package:sqflite_common/src/database.dart'; -import 'package:sqflite_common/src/database_mixin.dart'; -import 'package:sqflite_common/src/env_utils.dart'; -import 'package:sqflite_common/src/factory.dart'; -import 'package:sqflite_common/src/factory_mixin.dart'; -import 'package:sqflite_common/src/sql_command.dart'; -import 'package:sqflite_common/src/transaction.dart'; - -/// Log helper to avoid overflow -String logTruncateAny(Object? value) { - return logTruncate(value?.toString() ?? ''); -} - -/// Log helper to avoid overflow -String logTruncate(String text, {int len = 256}) { - if (text.length > len) { - text = text.substring(0, len); - } - return text; -} - -/// Type of logging. For now, only all logs (no filtering) are supported. -enum SqfliteDatabaseFactoryLoggerType { - /// All logs are returned. default. For the 3rd party debugging. - all, - - /// Internal implementation invocation. For internal debugging. - /// - /// all events are SqfliteLoggerInvokeEvent - invoke, -} - -/// Logger event function. -typedef SqfliteLoggerEventFunction = void Function(SqfliteLoggerEvent event); - -/// Every operation/event is a command -abstract class SqfliteLoggerCommand { - /// Name of the command (insert/delete/update...) for display only. - String get name; - - /// Set on failure - Object? get error; -} - -/// Logger event. -abstract class SqfliteLoggerEvent implements SqfliteLoggerCommand { - /// Stopwatch. for performance testing. - Stopwatch? get sw; -} - -/// View helper -@visibleForTesting -abstract class SqfliteLoggerEventView implements SqfliteLoggerEvent { - /// Map view. - Map toMap(); -} - -abstract class _SqfliteLoggerEvent - implements SqfliteLoggerEvent, SqfliteLoggerEventView { - @override - late final Object? error; - - @override - late final Stopwatch? sw; - - _SqfliteLoggerEvent(this.sw, this.error); - - /// Allow late init. - _SqfliteLoggerEvent._(); - - @override - Map toMap() => { - if (sw != null) 'sw': '${sw!.elapsed}', - if (error != null) 'error': error - }; - - @override - String toString() => toLogString(toMap()); -} - -/// Generic method event. -abstract class SqfliteLoggerInvokeEvent extends SqfliteLoggerEvent { - /// Invoke method. - String get method; - - /// Invoke arguments. - Object? get arguments; - - /// The result (result can be null if error is null but cannot be non null if error is null). - Object? get result; -} - -/// Open db event -abstract class SqfliteLoggerDatabaseDeleteEvent extends SqfliteLoggerEvent { - /// Database path. - String? get path; -} - -/// Open db event -abstract class SqfliteLoggerDatabaseOpenEvent extends SqfliteLoggerEvent { - /// The options used. - OpenDatabaseOptions? get options; - - /// Invoke arguments. - String? get path; - - /// The resulting database on success - Database? get db; -} - -/// Open db event -abstract class SqfliteLoggerDatabaseCloseEvent extends SqfliteLoggerEvent { - /// The closed database. - Database? get db; -} - -/// In database event. -abstract class SqfliteLoggerDatabaseEvent implements SqfliteLoggerEvent { - /// The database client (transaction or database) - DatabaseExecutor get client; -} - -/// Open db event -abstract class SqfliteLoggerSqlEvent extends SqfliteLoggerDatabaseEvent - implements SqfliteLoggerSqlCommand {} - -/// Typed sql command -abstract class SqfliteLoggerSqlCommand implements SqfliteLoggerCommand { - /// The command type. - SqliteSqlCommandType get type; - - /// Invoke arguments. - String get sql; - - /// Sql arguments. - Object? get arguments; - - /// Optional result. - T? get result; -} - -/// batch event -abstract class SqfliteLoggerBatchEvent extends SqfliteLoggerDatabaseEvent { - /// batch operations. - List get operations; -} - -/// Sql batch operation. -abstract class SqfliteLoggerBatchOperation - implements SqfliteLoggerSqlCommand {} - -mixin _SqfliteLoggerSqlCommandMixin implements SqfliteLoggerSqlCommand { - @override - late final SqliteSqlCommandType type; - - /// Invoke arguments. - @override - late final String sql; - - /// Sql arguments. - @override - late final Object? arguments; - - /// Optional result. - @override - late final T? result; - - String get _typeAsText => type.toString().split('.').last; -} - -abstract class _SqfliteLoggerDatabaseEvent extends _SqfliteLoggerEvent - implements SqfliteLoggerDatabaseEvent { - late final DatabaseExecutor _client; - - @override - DatabaseExecutor get client => _client; - - set client(DatabaseExecutor client) { - _client = client; - // save txn id right away to handle when not set yet. - txnId = (client as SqfliteDatabaseExecutorMixin).txn?.transactionId; - } - - Map get _databasePrefixMap => { - if (client.database is SqfliteDatabase) - 'db': (client.database as SqfliteDatabase).id, - if (txnId != null) 'txn': txnId - }; - - late int? txnId; - - @override - Map toMap() => {..._databasePrefixMap, ...super.toMap()}; - - _SqfliteLoggerDatabaseEvent(super.sw, DatabaseExecutor client, super.error) { - this.client = client; - } - - /// Allow late init. - _SqfliteLoggerDatabaseEvent._() : super._(); -} - -/// Event or batch operation execute command return a count. -abstract class SqfliteLoggerSqlCommandExecute - extends SqfliteLoggerSqlCommand {} - -/// Event or batch operation insert command return a record id. -abstract class SqfliteLoggerSqlCommandInsert - extends SqfliteLoggerSqlCommand {} - -/// Event or batch operation update command return a count. -abstract class SqfliteLoggerSqlCommandUpdate - extends SqfliteLoggerSqlCommand {} - -/// Event or batch operation delete command return a count. -abstract class SqfliteLoggerSqlCommandDelete - extends SqfliteLoggerSqlCommand {} - -/// Event or batch operation query command. -abstract class SqfliteLoggerSqlCommandQuery - extends SqfliteLoggerSqlCommand>> {} - -mixin _SqfliteLoggerSqlCommandInsertMixin { - String get name => 'insert'; -} -mixin _SqfliteLoggerSqlCommandExecuteMixin { - String get name => 'execute'; -} -mixin _SqfliteLoggerSqlCommandUpdateMixin { - String get name => 'update'; -} - -mixin _SqfliteLoggerSqlCommandDeleteMixin { - String get name => 'delete'; -} - -mixin _SqfliteLoggerSqlCommandQueryMixin { - String get name => 'query'; -} - -class _SqfliteLoggerSqlEventInsert extends _SqfliteLoggerSqlEvent - with _SqfliteLoggerSqlCommandInsertMixin - implements SqfliteLoggerSqlCommandInsert {} - -class _SqfliteLoggerSqlEventExecute extends _SqfliteLoggerSqlEvent - with _SqfliteLoggerSqlCommandExecuteMixin - implements SqfliteLoggerSqlCommandExecute {} - -class _SqfliteLoggerSqlEventUpdate extends _SqfliteLoggerSqlEvent - with _SqfliteLoggerSqlCommandUpdateMixin - implements SqfliteLoggerSqlCommandUpdate {} - -class _SqfliteLoggerSqlEventDelete extends _SqfliteLoggerSqlEvent - with _SqfliteLoggerSqlCommandDeleteMixin - implements SqfliteLoggerSqlCommandDelete {} - -class _SqfliteLoggerSqlEventQuery - extends _SqfliteLoggerSqlEvent>> - with _SqfliteLoggerSqlCommandQueryMixin - implements SqfliteLoggerSqlCommandQuery {} - -abstract class _SqfliteLoggerSqlEvent extends _SqfliteLoggerDatabaseEvent - with _SqfliteLoggerSqlCommandMixin - implements SqfliteLoggerSqlEvent { - _SqfliteLoggerSqlEvent() : super._(); - - static _SqfliteLoggerSqlEvent fromDynamic( - Stopwatch sw, - DatabaseExecutor client, - SqliteSqlCommandType type, - String sql, - List? arguments, - Object? result, - Object? error) { - _SqfliteLoggerSqlEvent event; - switch (type) { - case SqliteSqlCommandType.execute: - event = _SqfliteLoggerSqlEventExecute(); - break; - case SqliteSqlCommandType.insert: - event = _SqfliteLoggerSqlEventInsert(); - break; - case SqliteSqlCommandType.update: - event = _SqfliteLoggerSqlEventUpdate(); - break; - case SqliteSqlCommandType.delete: - event = _SqfliteLoggerSqlEventDelete(); - break; - case SqliteSqlCommandType.query: - event = _SqfliteLoggerSqlEventQuery(); - break; - } - - event.type = type; - event.sql = sql; - event.arguments = arguments; - event.result = result; - event.error = error; - event.sw = sw; - event.client = client; - return event; - } - - @override - Map toMap() => { - ..._databasePrefixMap, - 'sql': sql, - if (arguments != null) 'arguments': arguments, - if (result != null) 'result': result, - ...super.toMap() - }; - - @override - String toString() => '$_typeAsText(${super.toString()})'; -} - -/// Open db event -class _SqfliteLoggerBatchEvent extends _SqfliteLoggerDatabaseEvent - implements SqfliteLoggerBatchEvent { - @override - String get name => 'batch'; - @override - final List operations; - - _SqfliteLoggerBatchEvent( - super.sw, super.client, this.operations, super.error); - - @override - Map toMap() => { - ..._databasePrefixMap, - 'operations': operations - .map((e) => (e as _SqfliteLoggerBatchOperation).toMap()) - .toList(), - ...super.toMap() - }; -} - -class _SqfliteLoggerBatchInsertOperation - extends _SqfliteLoggerBatchOperation - with _SqfliteLoggerSqlCommandInsertMixin - implements SqfliteLoggerSqlCommandInsert {} - -class _SqfliteLoggerBatchUpdateOperation - extends _SqfliteLoggerBatchOperation - with _SqfliteLoggerSqlCommandUpdateMixin - implements SqfliteLoggerSqlCommandUpdate {} - -class _SqfliteLoggerBatchDeleteOperation - extends _SqfliteLoggerBatchOperation - with _SqfliteLoggerSqlCommandDeleteMixin - implements SqfliteLoggerSqlCommandDelete {} - -class _SqfliteLoggerBatchExecuteOperation - extends _SqfliteLoggerBatchOperation - with _SqfliteLoggerSqlCommandExecuteMixin - implements SqfliteLoggerSqlCommandExecute {} - -class _SqfliteLoggerBatchQueryOperation - extends _SqfliteLoggerBatchOperation>> - with _SqfliteLoggerSqlCommandQueryMixin - implements SqfliteLoggerSqlCommandQuery {} - -/// Batch sql operation -abstract class _SqfliteLoggerBatchOperation - with _SqfliteLoggerSqlCommandMixin - implements SqfliteLoggerBatchOperation { - @override - late final Object? error; - - static _SqfliteLoggerBatchOperation fromDynamic(SqliteSqlCommandType type, - String sql, List? arguments, Object? result, Object? error) { - _SqfliteLoggerBatchOperation operation; - switch (type) { - case SqliteSqlCommandType.execute: - operation = _SqfliteLoggerBatchExecuteOperation(); - break; - case SqliteSqlCommandType.insert: - operation = _SqfliteLoggerBatchInsertOperation(); - break; - - case SqliteSqlCommandType.update: - operation = _SqfliteLoggerBatchUpdateOperation(); - break; - case SqliteSqlCommandType.delete: - operation = _SqfliteLoggerBatchDeleteOperation(); - break; - case SqliteSqlCommandType.query: - operation = _SqfliteLoggerBatchQueryOperation(); - break; - } - operation.type = type; - operation.sql = sql; - operation.arguments = arguments; - operation.result = result; - operation.error = error; - return operation; - } - - Map toMap() { - var map = { - 'sql': sql, - if (arguments != null) 'arguments': arguments, - if (result != null) 'result': result, - if (error != null) 'error': error - }; - return map; - } - - @override - String toString() => '$_typeAsText(${logTruncate(toMap().toString())})'; -} - -class _SqfliteLoggerDatabaseDeleteEvent extends _SqfliteLoggerEvent - implements SqfliteLoggerDatabaseDeleteEvent { - @override - final String path; - - @override - Map toMap() => { - 'path': path, - }; - - _SqfliteLoggerDatabaseDeleteEvent(super.sw, this.path, super.error); - - @override - String get name => 'deleteDatabase'; -} - -class _SqfliteLoggerDatabaseOpenEvent extends _SqfliteLoggerEvent - implements SqfliteLoggerDatabaseOpenEvent { - @override - final SqfliteDatabase? db; - - @override - final OpenDatabaseOptions? options; - - @override - final String path; - - @override - Map toMap() => { - 'path': path, - if (options != null) 'options': options!.toMap(), - if (db?.id != null) 'id': db!.id, - ...super.toMap() - }; - - _SqfliteLoggerDatabaseOpenEvent( - super.sw, this.path, this.options, this.db, super.error); - - @override - String get name => 'openDatabase'; -} - -class _SqfliteLoggerDatabaseCloseEvent extends _SqfliteLoggerDatabaseEvent - implements SqfliteLoggerDatabaseCloseEvent { - @override - Map toMap() => {..._databasePrefixMap, ...super.toMap()}; - - _SqfliteLoggerDatabaseCloseEvent(super.sw, super.db, super.error); - @override - String get name => 'closeDatabase'; - - @override - Database get db => client.database; -} - -class _SqfliteLoggerInvokeEvent extends _SqfliteLoggerEvent - implements SqfliteLoggerInvokeEvent { - @override - final Object? result; - - @override - final Object? arguments; - - @override - final String method; - - @override - Map toMap() => { - 'method': method, - if (arguments != null) 'arguments': arguments, - if (result != null) 'result': result, - ...super.toMap() - }; - - _SqfliteLoggerInvokeEvent( - super.sw, this.method, this.arguments, this.result, super.error); - - @override - String get name => 'invoke'; -} - -class _EventInfo { - Object? error; - StackTrace? stackTrace; - T? result; - final sw = Stopwatch()..start(); - - T throwOrResult() { - if (error != null) { - if (isDebug && (stackTrace != null)) { - print(stackTrace); - } - throw error!; - } - return result as T; - } -} - -/// Default logger. print! -void _logDefault(SqfliteLoggerEvent event) { - event.dump(); -} - -/// Default type, all! -var _typeDefault = SqfliteDatabaseFactoryLoggerType.all; - -/// Sqflite logger option. -/// -/// [type] default to [SqfliteDatabaseFactoryLoggerType.all] -/// [log] default to print. -class SqfliteLoggerOptions { - /// True if write should be logged - late final void Function(SqfliteLoggerEvent event) log; - - /// The logger type (filtering) - late final SqfliteDatabaseFactoryLoggerType type; - - /// Sqflite logger option. - SqfliteLoggerOptions( - {SqfliteLoggerEventFunction? log, - SqfliteDatabaseFactoryLoggerType? type}) { - this.log = log ?? _logDefault; - this.type = type ?? _typeDefault; - } -} - -/// Special wrapper that allows easily wrapping each API calls. -abstract class SqfliteDatabaseFactoryLogger implements SqfliteDatabaseFactory { - /// Wrap each call in a logger. - @experimental - factory SqfliteDatabaseFactoryLogger(DatabaseFactory factory, - {SqfliteLoggerOptions? options}) { - var delegate = factory; - if (factory is SqfliteDatabaseFactoryLogger) { - delegate = (factory as _SqfliteDatabaseFactoryLogger)._delegate; - } - return _SqfliteDatabaseFactoryLogger( - delegate as SqfliteDatabaseFactory, options ?? SqfliteLoggerOptions()); - } -} - -mixin _SqfliteDatabaseExecutorLoggerMixin implements SqfliteDatabaseExecutor { - SqfliteDatabaseExecutor _executor(SqfliteTransaction? txn) => - txn ?? this.txn ?? this; -} - -class _SqfliteDatabaseLogger extends SqfliteDatabaseBase - with _SqfliteDatabaseExecutorLoggerMixin - implements SqfliteDatabase { - late final _SqfliteDatabaseFactoryLogger _factory; - - SqfliteLoggerOptions get _options => _factory._options; - - @override - _SqfliteDatabaseFactoryLogger get factory => _factory; - - _SqfliteDatabaseLogger(SqfliteDatabaseOpenHelper openHelper, String path, - {OpenDatabaseOptions? options}) - : super(openHelper, path, options: options) { - _factory = openHelper.factory as _SqfliteDatabaseFactoryLogger; - } - - void _log(SqfliteLoggerEvent event) => _options.log(event); - - bool get _needLogAll => _options.type == SqfliteDatabaseFactoryLoggerType.all; - - @override - Future openDatabase() async { - Future doOpenDatabase() async { - return (await super.openDatabase()); - } - - if (!_needLogAll) { - return await doOpenDatabase(); - } else { - var info = await _wrap(doOpenDatabase); - _options.log(_SqfliteLoggerDatabaseOpenEvent( - info.sw, path, options, this, info.error)); - return info.throwOrResult(); - } - } - - @override - Future close() async { - Future doClose() { - return super.close(); - } - - if (_needLogAll) { - var info = await _wrap(doClose); - _log(_SqfliteLoggerDatabaseCloseEvent(info.sw, this, info.error)); - info.throwOrResult(); - } else { - await doClose(); - } - } - - /// Commit a batch. - @override - Future> txnApplyBatch( - SqfliteTransaction? txn, SqfliteBatch batch, - {bool? noResult, bool? continueOnError}) async { - Future> doApplyBatch() { - return super.txnApplyBatch(txn, batch, - noResult: noResult, continueOnError: continueOnError); - } - - if (_needLogAll) { - var info = await _wrap(doApplyBatch); - - var logOperations = <_SqfliteLoggerBatchOperation>[]; - if (info.error == null) { - var operations = batch.operations; - - for (var i = 0; i < operations.length; i++) { - var operation = operations[i]; - Object? result; - Object? error; - if (noResult != true) { - var resultOrError = info.result![i]; - if (resultOrError is DatabaseException) { - error = resultOrError; - } else { - result = resultOrError; - } - } - logOperations.add(_SqfliteLoggerBatchOperation.fromDynamic( - operation.type, - operation.sql, - operation.arguments, - result, - error)); - } - } - _options.log(_SqfliteLoggerBatchEvent( - info.sw, _executor(txn), logOperations, info.error)); - return info.throwOrResult(); - } else { - return await doApplyBatch(); - } - } - - /// Execute a raw SQL SELECT query - /// - /// Returns a list of rows that were found - @override - Future>> txnRawQuery( - SqfliteTransaction? txn, String sql, List? arguments) { - return _txnWrapSql(txn, SqliteSqlCommandType.query, sql, arguments, - () async { - return super.txnRawQuery(txn, sql, arguments); - }); - } - - @override - Future txnRawDelete( - SqfliteTransaction? txn, String sql, List? arguments) { - return _txnWrapSql(txn, SqliteSqlCommandType.delete, sql, arguments, - () async { - return super.txnRawDelete(txn, sql, arguments); - }); - } - - @override - Future txnRawUpdate( - SqfliteTransaction? txn, String sql, List? arguments) { - return _txnWrapSql(txn, SqliteSqlCommandType.update, sql, arguments, - () async { - return super.txnRawUpdate(txn, sql, arguments); - }); - } - - /// for INSERT sql query - /// returns the last inserted record id - /// - /// 0 returned instead of null - @override - Future txnRawInsert( - SqfliteTransaction? txn, String sql, List? arguments) { - return _txnWrapSql(txn, SqliteSqlCommandType.insert, sql, arguments, - () async { - return super.txnRawInsert(txn, sql, arguments); - }); - } - - /// Execute a command. - @override - Future txnExecute( - SqfliteTransaction? txn, String sql, List? arguments, - {bool? beginTransaction}) { - return _txnWrapSql( - txn, - SqliteSqlCommandType.execute, - sql, - arguments, - () => super.txnExecute(txn, sql, arguments, - beginTransaction: beginTransaction)); - } - - Future _txnWrapSql(SqfliteTransaction? txn, SqliteSqlCommandType type, - String sql, List? arguments, Future Function() action) async { - if (!_needLogAll) { - return await action(); - } else { - var info = await _wrap(action); - _options.log(_SqfliteLoggerSqlEvent.fromDynamic(info.sw, _executor(txn), - type, sql, arguments, info.result, info.error)); - return info.throwOrResult(); - } - } - - Future<_EventInfo> _wrap(FutureOr Function() action) => - _factory._wrap(action); -} - -class _SqfliteDatabaseFactoryLogger - with SqfliteDatabaseFactoryMixin - implements SqfliteDatabaseFactoryLogger { - final SqfliteDatabaseFactory _delegate; - final SqfliteLoggerOptions _options; - - _SqfliteDatabaseFactoryLogger(this._delegate, this._options); - - // Needed for proper exception conversion. - @override - Future wrapDatabaseException(Future Function() action) => - _delegate.wrapDatabaseException(action); - - /// The only method to override to create a custom object. - @override - SqfliteDatabaseMixin newDatabase( - SqfliteDatabaseOpenHelper openHelper, String path) { - return _SqfliteDatabaseLogger(openHelper, path); - } - - Future<_EventInfo> _wrap(FutureOr Function() action) async { - var info = _EventInfo(); - try { - var result = await action(); - info.result = result; - } catch (error, stackTrace) { - info.error = error; - if (isDebug) { - info.stackTrace = stackTrace; - } - } finally { - info.sw.stop(); - } - return info; - } - - /// The only method to override to use the delegate - @override - Future invokeMethod(String method, [Object? arguments]) async { - Future doInvokeMethod() { - return _delegate.invokeMethod(method, arguments); - } - - if (_options.type == SqfliteDatabaseFactoryLoggerType.invoke) { - var info = await _wrap(doInvokeMethod); - _options.log(_SqfliteLoggerInvokeEvent( - info.sw, method, arguments, info.result, info.error)); - return info.throwOrResult(); - } else { - return await doInvokeMethod(); - } - } - - @override - Future deleteDatabase(String path) async { - Future doDeleteDatabase() { - return super.deleteDatabase(path); - } - - if (_options.type == SqfliteDatabaseFactoryLoggerType.all) { - var info = await _wrap(doDeleteDatabase); - _options - .log(_SqfliteLoggerDatabaseDeleteEvent(info.sw, path, info.error)); - return info.throwOrResult(); - } else { - return await doDeleteDatabase(); - } - } -} - -/// internal extension. -@visibleForTesting -extension OpenDatabaseOptionsLogger on OpenDatabaseOptions { - /// To map view - Map toMap() => { - 'readOnly': readOnly, - 'singleInstance': singleInstance, - if (version != null) 'version': version - }; -} - -/// Basic dump -extension SqfliteLoggerEventExt on SqfliteLoggerEvent { - /// dump event by lines - void dump({void Function(Object? object)? print, bool? noStopwatch}) { - print ??= core.print; - - if (this is SqfliteLoggerBatchEvent) { - if (noStopwatch ?? false) { - print(toLogString(toMapNoOperationsNoStopwatch())); - } else { - print(toLogString(toMapNoOperations())); - } - for (var operation in (this as SqfliteLoggerBatchEvent).operations) { - print(' $operation'); - } - } else { - // default to improve - if (noStopwatch ?? false) { - print(toStringNoStopwatch()); - } else { - print(toString()); - } - } - } -} - -/// Not exported. -extension SqfliteLoggerEventInternalExt on SqfliteLoggerEvent { - /// Internal only. - Map toMapNoStopwatch() { - return (Map.from((this as SqfliteLoggerEventView).toMap())) - ..remove('sw'); - } - - /// Internal only. - Map toMapNoOperations() { - return (Map.from((this as SqfliteLoggerEventView).toMap())) - ..remove('operations'); - } - - /// Internal only. - Map toMapNoOperationsNoStopwatch() { - return (toMapNoStopwatch())..remove('operations'); - } - - /// Internal only, prefix with the event name. - String toLogString(Object? data) => logTruncate('$name:($data)'); - - /// Internal only. - String toStringNoStopwatch() => toLogString(toMapNoStopwatch()); -} - -/// Debug extension for Logger. -extension DatabaseFactoryLoggerDebugExt on DatabaseFactory { - /// Quick logger wrapper, useful in unit test. - /// - /// databaseFactory = databaseFactory.debugQuickLoggerWrapper() - @Deprecated('Debug/dev mode') - DatabaseFactory debugQuickLoggerWrapper() { - var factoryWithLogs = SqfliteDatabaseFactoryLogger(this, - options: - SqfliteLoggerOptions(type: SqfliteDatabaseFactoryLoggerType.all)); - return factoryWithLogs; - } -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/method_call.dart b/sqflite/tripartite/sqflite_common/lib/src/method_call.dart deleted file mode 100644 index cb54f1b08e9534c8409a91852d51e530b4bb4ab7..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/method_call.dart +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:meta/meta.dart'; - -/// An command object representing the invocation of a named method. -@immutable -class SqfliteMethodCall { - /// Creates a [MethodCall] representing the invocation of [method] with the - /// specified [arguments]. - const SqfliteMethodCall(this.method, [this.arguments]); - - /// Build from a map. - factory SqfliteMethodCall.fromMap(Map map) { - return SqfliteMethodCall(map['method'] as String, map['arguments']); - } - - /// The name of the method to be called. - final String method; - - /// The arguments for the method. - /// - /// Must be a valid value for the [MethodCodec] used. - final Object? arguments; - - /// To map - Map toMap() { - return { - 'method': method, - if (arguments != null) 'arguments': arguments - }; - } - - @override - String toString() => '$runtimeType($method, $arguments)'; -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/mixin.dart b/sqflite/tripartite/sqflite_common/lib/src/mixin.dart deleted file mode 100644 index 089c49d8bace614730e0c7ceb6c5e07bda56c1c2..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/mixin.dart +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/// Sqflite mixins -/// -/// Warning the API here are exposed to external implementation -export 'database_mixin.dart'; -export 'factory_mixin.dart'; diff --git a/sqflite/tripartite/sqflite_common/lib/src/mixin/constant.dart b/sqflite/tripartite/sqflite_common/lib/src/mixin/constant.dart deleted file mode 100644 index 61a934b1224e95380de376167d1269e296cc6a00..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/mixin/constant.dart +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export 'package:sqflite_common/src/constant.dart' hide methodSetDebugModeOn; diff --git a/sqflite/tripartite/sqflite_common/lib/src/mixin/dev_utils.dart b/sqflite/tripartite/sqflite_common/lib/src/mixin/dev_utils.dart deleted file mode 100644 index 047e27dd74004363ff19ecc62b99f9256115a775..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/mixin/dev_utils.dart +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// ignore: deprecated_member_use, deprecated_member_use_from_same_package -export 'package:sqflite_common/src/dev_utils.dart' show devPrint, devWarning; diff --git a/sqflite/tripartite/sqflite_common/lib/src/mixin/factory.dart b/sqflite/tripartite/sqflite_common/lib/src/mixin/factory.dart deleted file mode 100644 index 8dd51966d6358f68e8a8ff5c64e48fbf64228b8b..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/mixin/factory.dart +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/factory_mixin.dart'; - -/// Mixin handler -abstract class SqfliteInvokeHandler { - /// Invoke method - Future invokeMethod(String method, [Object? arguments]); -} - -class _SqfliteDatabaseFactoryImpl - with SqfliteDatabaseFactoryMixin - implements SqfliteInvokeHandler { - _SqfliteDatabaseFactoryImpl(this._invokeMethod, {String? tag}) { - this.tag = tag; - } - - final Future Function(String method, [Object? arguments]) - _invokeMethod; - - @override - Future invokeMethod(String method, [Object? arguments]) async => - (await _invokeMethod(method, arguments)) as T; -} - -/// Build a database factory invoking the invoke method instead of going through -/// flutter services. -/// -/// To use to enable running without flutter plugins (unit test) -/// -/// [tag] is an optional debug -DatabaseFactory buildDatabaseFactory( - {String? tag, - required Future Function(String method, [Object? arguments]) - invokeMethod}) { - final DatabaseFactory impl = - _SqfliteDatabaseFactoryImpl(invokeMethod, tag: tag); - return impl; -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/mixin/import_mixin.dart b/sqflite/tripartite/sqflite_common/lib/src/mixin/import_mixin.dart deleted file mode 100644 index 30be01369ce8faa9ceec3e9fd2bdf1745f4ed0b7..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/mixin/import_mixin.dart +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/// -/// Export for implementation: sqflite, sqflite_common_ffi -/// -export 'package:sqflite_common/src/compat.dart' - show - SqfliteOptions; // ignore: deprecated_member_use, deprecated_member_use_from_same_package -/// Explicit list of needed private import -export 'package:sqflite_common/src/database.dart' // ignore: implementation_imports - show - SqfliteDatabaseOpenHelper, - SqfliteDatabase; -export 'package:sqflite_common/src/database_mixin.dart' // ignore: implementation_imports - show - SqfliteDatabaseMixin, - SqfliteDatabaseBase; - -// -// Exception -// -export 'package:sqflite_common/src/exception.dart' - show SqfliteDatabaseException; -export 'package:sqflite_common/src/factory.dart' show SqfliteDatabaseFactory; - -// -// Factory mixin -// -export 'package:sqflite_common/src/factory_mixin.dart' - show SqfliteDatabaseFactoryBase, SqfliteDatabaseFactoryMixin; - -// -// Constant -// -export 'package:sqflite_common/src/mixin/constant.dart' - show - methodOpenDatabase, - methodCloseDatabase, - methodOptions, - methodInsert, - methodQuery, - methodUpdate, - methodExecute, - methodBatch, - sqliteErrorCode; -export 'package:sqflite_common/src/mixin/factory.dart' - show buildDatabaseFactory, SqfliteInvokeHandler; diff --git a/sqflite/tripartite/sqflite_common/lib/src/open_options.dart b/sqflite/tripartite/sqflite_common/lib/src/open_options.dart deleted file mode 100644 index ac754a5b106454f6300696b67d5c21d84eba70cd..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/open_options.dart +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; - -/// -/// Options to open a database -/// See [openDatabase] for details -/// -class SqfliteOpenDatabaseOptions implements OpenDatabaseOptions { - /// See [openDatabase] for details - SqfliteOpenDatabaseOptions({ - this.version, - this.onConfigure, - this.onCreate, - this.onUpgrade, - this.onDowngrade, - this.onOpen, - bool? readOnly = false, - bool? singleInstance = true, - }) : readOnly = readOnly ?? false, - singleInstance = singleInstance ?? true; - - @override - int? version; - @override - OnDatabaseConfigureFn? onConfigure; - @override - OnDatabaseCreateFn? onCreate; - @override - OnDatabaseVersionChangeFn? onUpgrade; - @override - OnDatabaseVersionChangeFn? onDowngrade; - @override - OnDatabaseOpenFn? onOpen; - @override - bool readOnly; - @override - bool singleInstance; - - @override - String toString() { - final map = {}; - if (version != null) { - map['version'] = version; - } - map['readOnly'] = readOnly; - map['singleInstance'] = singleInstance; - return map.toString(); - } -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/path_utils.dart b/sqflite/tripartite/sqflite_common/lib/src/path_utils.dart deleted file mode 100644 index 5e3c1a89e70ef9d7999790ccf47599e0e6a6b5e0..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/path_utils.dart +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; - -const _fileUriPrefix = 'file:'; - -/// True if a database path is in memory -bool isInMemoryDatabasePath(String path) { - if (path == inMemoryDatabasePath) { - return true; - } - if (isFileUriDatabasePath(path)) { - if (path.substring(_fileUriPrefix.length) == inMemoryDatabasePath) { - return true; - } - } - return false; -} - -/// True if a database path is a file uri -bool isFileUriDatabasePath(String path) { - return path.startsWith(_fileUriPrefix); -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/platform/platform.dart b/sqflite/tripartite/sqflite_common/lib/src/platform/platform.dart deleted file mode 100644 index 0374c6fb1d13ca565d9b727e26ebd23d91520d4e..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/platform/platform.dart +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export 'platform_io.dart' if (dart.library.js) 'platform_web.dart'; - -/// IO/web support -abstract class Platform { - /// True if web - bool get isWeb => false; - - /// True if IO windows - bool get isWindows => false; - - /// True if IO ios - bool get isIOS => false; - - /// True if IO Android - bool get isAndroid => false; - - /// True if IO Linux - bool get isLinux => false; - - /// True if IO MacOS - bool get isMacOS => false; -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/platform/platform_io.dart b/sqflite/tripartite/sqflite_common/lib/src/platform/platform_io.dart deleted file mode 100644 index 59ef7b67114066798384358d3c6bd469e6635356..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/platform/platform_io.dart +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'dart:io' as io; - -import 'package:sqflite_common/src/platform/platform.dart'; - -class _PlatformIo extends Platform { - @override - bool get isWindows => io.Platform.isWindows; - - @override - bool get isIOS => io.Platform.isIOS; - - @override - bool get isAndroid => io.Platform.isAndroid; - - @override - bool get isLinux => io.Platform.isLinux; - - @override - bool get isMacOS => io.Platform.isMacOS; -} - -/// Platform (IO) -final platform = _PlatformIo(); diff --git a/sqflite/tripartite/sqflite_common/lib/src/platform/platform_web.dart b/sqflite/tripartite/sqflite_common/lib/src/platform/platform_web.dart deleted file mode 100644 index 2044654642023718b99bc96ed075eae8a5f17f71..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/platform/platform_web.dart +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/src/platform/platform.dart'; - -class _PlatformWeb extends Platform { - @override - bool get isWeb => false; -} - -/// Platform (Web) -final platform = _PlatformWeb(); diff --git a/sqflite/tripartite/sqflite_common/lib/src/sqflite_database_factory.dart b/sqflite/tripartite/sqflite_common/lib/src/sqflite_database_factory.dart deleted file mode 100644 index a8a0ccf61c380a9f276702a3ee698c006b022104..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/sqflite_database_factory.dart +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:meta/meta.dart'; -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/factory.dart'; - -SqfliteDatabaseFactory? _databaseFactory; - -/// Default database factory. -@visibleForTesting -DatabaseFactory? get databaseFactoryOrNull => _databaseFactory; - -/// Change the default factory. -set databaseFactoryOrNull(DatabaseFactory? databaseFactory) { - if (databaseFactory != null) { - if (databaseFactory is! SqfliteDatabaseFactory) { - throw ArgumentError.value( - databaseFactory, 'databaseFactory', 'Unsupported sqflite factory'); - } - _databaseFactory = databaseFactory; - } else { - /// Unset - _databaseFactory = null; - } -} - -/// sqflite Default factory. -DatabaseFactory get databaseFactory => - _databaseFactory ?? - () { - throw StateError('''databaseFactory not initialized -databaseFactory is only initialized when using sqflite. When using `sqflite_common_ffi` -You must call `databaseFactory = databaseFactoryFfi;` before using global openDatabase API -'''); - }(); - -/// Change the default factory. -/// -/// Be aware of the potential side effect. Any library using sqflite -/// will have this factory as the default for all operations. -/// -/// This setter must be call only once, before any other calls to sqflite. -set databaseFactory(DatabaseFactory? databaseFactory) { - // Warn when changing. might throw in the future - if (databaseFactory != null) { - if (_databaseFactory != null) { - print(''' -*** sqflite warning *** - -You are changing sqflite default factory. -Be aware of the potential side effects. Any library using sqflite -will have this factory as the default for all operations. - -*** sqflite warning *** -'''); - } - } - databaseFactoryOrNull = databaseFactory; -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/sqflite_debug.dart b/sqflite/tripartite/sqflite_common/lib/src/sqflite_debug.dart deleted file mode 100644 index a4679980b702e4765e6430d80d67b062fc3a2191..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/sqflite_debug.dart +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; - -import 'mixin/import_mixin.dart'; -export 'logger/sqflite_logger.dart' show DatabaseFactoryLoggerDebugExt; - -/// Debug extension -/// -/// Access to dev options, deprecated for temp usage only -extension SqfliteDatabaseFactoryDebug on DatabaseFactory { - /// Change the log level if you want to see the SQL query - /// executed natively. - /// - /// Deprecated for temp usage only - @Deprecated('Dev only') - Future debugSetLogLevel(int logLevel) async { - await debugSetOptions(SqfliteOptions(logLevel: logLevel)); - } - - /// Testing only. - /// - /// deprecated on purpose to remove from code. - @Deprecated('Dev only') - Future debugSetOptions(SqfliteOptions options) async { - await (this as SqfliteInvokeHandler) - .invokeMethod(methodOptions, options.toMap()); - } -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/sqflite_import.dart b/sqflite/tripartite/sqflite_common/lib/src/sqflite_import.dart deleted file mode 100644 index 870bbaf2c90670aee3ea518aa22445a00d68183c..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/sqflite_import.dart +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/// -/// Export for implementation: sqflite, sqflite_common_ffi -/// -export 'package:sqflite_common/src/compat.dart' - show SqfliteOptions; // ignore: deprecated_member_use_from_same_package -/// Explicit list of needed private import -export 'package:sqflite_common/src/database.dart' // ignore: implementation_imports - show - SqfliteDatabaseOpenHelper, - SqfliteDatabase; -export 'package:sqflite_common/src/database_mixin.dart' // ignore: implementation_imports - show - SqfliteDatabaseMixin, - SqfliteDatabaseBase; -export 'package:sqflite_common/src/exception.dart' - show SqfliteDatabaseException; -export 'package:sqflite_common/src/factory.dart' show SqfliteDatabaseFactory; -export 'package:sqflite_common/src/factory_mixin.dart' - show SqfliteDatabaseFactoryBase, SqfliteDatabaseFactoryMixin; -export 'package:sqflite_common/src/mixin/constant.dart' - show - methodOpenDatabase, - methodCloseDatabase, - methodOptions, - sqliteErrorCode, - methodInsert, - methodQuery, - methodUpdate, - methodExecute, - methodBatch; -export 'package:sqflite_common/src/mixin/factory.dart' - show buildDatabaseFactory, SqfliteInvokeHandler; diff --git a/sqflite/tripartite/sqflite_common/lib/src/sql_builder.dart b/sqflite/tripartite/sqflite_common/lib/src/sql_builder.dart deleted file mode 100644 index 1e2de09193ab669ff01b0056eaeb8fc16adfcfd7..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/sql_builder.dart +++ /dev/null @@ -1,612 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/src/value_utils.dart'; - -/// Insert/Update conflict resolver -enum ConflictAlgorithm { - /// When a constraint violation occurs, an immediate ROLLBACK occurs, - /// thus ending the current transaction, and the command aborts with a - /// return code of SQLITE_CONSTRAINT. If no transaction is active - /// (other than the implied transaction that is created on every command) - /// then this algorithm works the same as ABORT. - rollback, - - /// When a constraint violation occurs,no ROLLBACK is executed - /// so changes from prior commands within the same transaction - /// are preserved. This is the default behavior. - abort, - - /// When a constraint violation occurs, the command aborts with a return - /// code SQLITE_CONSTRAINT. But any changes to the database that - /// the command made prior to encountering the constraint violation - /// are preserved and are not backed out. - fail, - - /// When a constraint violation occurs, the one row that contains - /// the constraint violation is not inserted or changed. - /// But the command continues executing normally. Other rows before and - /// after the row that contained the constraint violation continue to be - /// inserted or updated normally. No error is returned. - ignore, - - /// When a UNIQUE constraint violation occurs, the pre-existing rows that - /// are causing the constraint violation are removed prior to inserting - /// or updating the current row. Thus the insert or update always occurs. - /// The command continues executing normally. No error is returned. - /// If a NOT NULL constraint violation occurs, the NULL value is replaced - /// by the default value for that column. If the column has no default - /// value, then the ABORT algorithm is used. If a CHECK constraint - /// violation occurs then the IGNORE algorithm is used. When this conflict - /// resolution strategy deletes rows in order to satisfy a constraint, - /// it does not invoke delete triggers on those rows. - /// This behavior might change in a future release. - replace, -} - -final List _conflictValues = [ - 'OR ROLLBACK', - 'OR ABORT', - 'OR FAIL', - 'OR IGNORE', - 'OR REPLACE' -]; - -//final RegExp _sLimitPattern = new RegExp('\s*\d+\s*(,\s*\d+\s*)?'); - -/// SQL command builder. -class SqlBuilder { - /// Convenience method for deleting rows in the database. - /// - /// @param table the table to delete from - /// @param where the optional WHERE clause to apply when deleting. - /// Passing null will delete all rows. - /// @param whereArgs You may include ?s in the where clause, which - /// will be replaced by the values from whereArgs. The values - /// will be bound as Strings. - SqlBuilder.delete(String table, {String? where, List? whereArgs}) { - checkWhereArgs(whereArgs); - final delete = StringBuffer(); - delete.write('DELETE FROM '); - delete.write(_escapeName(table)); - _writeClause(delete, ' WHERE ', where); - sql = delete.toString(); - arguments = whereArgs != null ? List.from(whereArgs) : null; - } - - /// Build an SQL query string from the given clauses. - /// - /// @param distinct true if you want each row to be unique, false otherwise. - /// @param table The table names to compile the query against. - /// @param columns A list of which columns to return. Passing null will - /// return all columns, which is discouraged to prevent reading - /// data from storage that isn't going to be used. - /// @param where A filter declaring which rows to return, formatted as an SQL - /// WHERE clause (excluding the WHERE itself). Passing null will - /// return all rows for the given URL. - /// @param groupBy A filter declaring how to group rows, formatted as an SQL - /// GROUP BY clause (excluding the GROUP BY itself). Passing null - /// will cause the rows to not be grouped. - /// @param having A filter declare which row groups to include in the cursor, - /// if row grouping is being used, formatted as an SQL HAVING - /// clause (excluding the HAVING itself). Passing null will cause - /// all row groups to be included, and is required when row - /// grouping is not being used. - /// @param orderBy How to order the rows, formatted as an SQL ORDER BY clause - /// (excluding the ORDER BY itself). Passing null will use the - /// default sort order, which may be unordered. - /// @param limit Limits the number of rows returned by the query, - /// formatted as LIMIT clause. Passing null denotes no LIMIT clause. - SqlBuilder.query(String table, - {bool? distinct, - List? columns, - String? where, - List? whereArgs, - String? groupBy, - String? having, - String? orderBy, - int? limit, - int? offset}) { - if (groupBy == null && having != null) { - throw ArgumentError( - 'HAVING clauses are only permitted when using a groupBy clause'); - } - checkWhereArgs(whereArgs); - - final query = StringBuffer(); - - query.write('SELECT '); - if (distinct == true) { - query.write('DISTINCT '); - } - if (columns != null && columns.isNotEmpty) { - _writeColumns(query, columns); - } else { - query.write('* '); - } - query.write('FROM '); - query.write(_escapeName(table)); - _writeClause(query, ' WHERE ', where); - _writeClause(query, ' GROUP BY ', groupBy); - _writeClause(query, ' HAVING ', having); - _writeClause(query, ' ORDER BY ', orderBy); - if (limit != null) { - _writeClause(query, ' LIMIT ', limit.toString()); - } - if (offset != null) { - _writeClause(query, ' OFFSET ', offset.toString()); - } - - sql = query.toString(); - arguments = whereArgs != null ? List.from(whereArgs) : null; - } - - /// Convenience method for inserting a row into the database. - /// Parameters: - /// @table the table to insert the row into - /// @nullColumnHack optional; may be null. SQL doesn't allow inserting a completely empty row without naming at least one column name. If your provided values is empty, no column names are known and an empty row can't be inserted. If not set to null, the nullColumnHack parameter provides the name of nullable column name to explicitly insert a NULL into in the case where your values is empty. - /// @values this map contains the initial column values for the row. The keys should be the column names and the values the column values - - SqlBuilder.insert(String table, Map values, - {String? nullColumnHack, ConflictAlgorithm? conflictAlgorithm}) { - final insert = StringBuffer(); - insert.write('INSERT'); - if (conflictAlgorithm != null) { - insert.write(' ${_conflictValues[conflictAlgorithm.index]}'); - } - insert.write(' INTO '); - insert.write(_escapeName(table)); - insert.write(' ('); - - List? bindArgs; - final size = values.length; - - if (size > 0) { - final sbValues = StringBuffer(') VALUES ('); - - bindArgs = []; - var i = 0; - values.forEach((String colName, Object? value) { - if (i++ > 0) { - insert.write(', '); - sbValues.write(', '); - } - - /// This should be just a column name - insert.write(_escapeName(colName)); - if (value == null) { - sbValues.write('NULL'); - } else { - checkNonNullValue(value); - bindArgs!.add(value); - sbValues.write('?'); - } - }); - insert.write(sbValues); - } else { - if (nullColumnHack == null) { - throw ArgumentError('nullColumnHack required when inserting no data'); - } - insert.write('$nullColumnHack) VALUES (NULL'); - } - insert.write(')'); - - sql = insert.toString(); - arguments = bindArgs; - } - - /// Convenience method for updating rows in the database. - /// - /// @param table the table to update in - /// @param values a map from column names to new column values. null is a - /// valid value that will be translated to NULL. - /// @param whereClause the optional WHERE clause to apply when updating. - /// Passing null will update all rows. - /// @param whereArgs You may include ?s in the where clause, which - /// will be replaced by the values from whereArgs. The values - /// will be bound as Strings. - /// @param conflictAlgorithm for update conflict resolver - - SqlBuilder.update(String table, Map values, - {String? where, - List? whereArgs, - ConflictAlgorithm? conflictAlgorithm}) { - if (values.isEmpty) { - throw ArgumentError('Empty values'); - } - checkWhereArgs(whereArgs); - - final update = StringBuffer(); - update.write('UPDATE'); - if (conflictAlgorithm != null) { - update.write(' ${_conflictValues[conflictAlgorithm.index]}'); - } - update.write(' ${_escapeName(table)}'); - update.write(' SET '); - - final bindArgs = []; - var i = 0; - - for (var colName in values.keys) { - update.write((i++ > 0) ? ', ' : ''); - update.write(_escapeName(colName)); - final value = values[colName]; - if (value != null) { - checkNonNullValue(value); - bindArgs.add(value); - update.write(' = ?'); - } else { - update.write(' = NULL'); - } - } - - if (whereArgs != null) { - bindArgs.addAll(whereArgs); - } - - _writeClause(update, ' WHERE ', where); - - sql = update.toString(); - arguments = bindArgs; - } - - /// The resulting SQL command. - late String sql; - - /// The arguments list; - List? arguments; - - /// Used during build if there was a name with an escaped keyword. - bool hasEscape = false; - - String _escapeName(String name) => escapeName(name); - - void _writeClause(StringBuffer s, String name, String? clause) { - if (clause != null) { - s.write(name); - s.write(clause); - } - } - - /// Add the names that are non-null in columns to s, separating - /// them with commas. - void _writeColumns(StringBuffer s, List columns) { - final n = columns.length; - - for (var i = 0; i < n; i++) { - final column = columns[i]; - - if (i > 0) { - s.write(', '); - } - s.write(_escapeName(column)); - } - s.write(' '); - } -} - -/// True if a name had been escaped already. -bool isEscapedName(String name) { - if (name.length >= 2) { - final codeUnits = name.codeUnits; - if (_areCodeUnitsEscaped(codeUnits)) { - return escapeNames - .contains(name.substring(1, name.length - 1).toLowerCase()); - } - } - return false; -} - -// The actual escape implementation -// We use double quote, although backtick could be used too -String _doEscape(String name) => '"$name"'; - -/// Escape a table or column name if necessary. -/// -/// i.e. if it is an identified it will be surrounded by " (double-quote) -/// Only some name belonging to keywords can be escaped -String escapeName(String name) { - if (escapeNames.contains(name.toLowerCase())) { - return _doEscape(name); - } - return name; -} - -/// Unescape a table or column name. -String unescapeName(String name) { - if (isEscapedName(name)) { - return name.substring(1, name.length - 1); - } - return name; -} - -/// Escape a column name if necessary. -/// -/// Only for insert and update keys -String escapeEntityName(String name) { - if (_entityNameNeedEscape(name)) { - return _doEscape(name); - } - return name; -} - -const _lowercaseA = 0x61; -const _lowercaseZ = 0x7A; - -const _underscore = 0x5F; -const _digit0 = 0x30; -const _digit9 = 0x39; - -const _backtick = 0x60; -const _doubleQuote = 0x22; -const _singleQuote = 0x27; - -const _uppercaseA = 0x41; -const _uppercaseZ = 0x5A; - -/// Returns `true` if [codeUnit] represents a digit. -/// -/// The definition of digit matches the Unicode `0x3?` range of Western -/// European digits. -bool _isDigit(int codeUnit) => codeUnit >= _digit0 && codeUnit <= _digit9; - -/// Returns `true` if [codeUnit] represents matchs azAZ_. -bool _isAlphaOrUnderscore(int codeUnit) => - (codeUnit >= _lowercaseA && codeUnit <= _lowercaseZ) || - (codeUnit >= _uppercaseA && codeUnit <= _uppercaseZ) || - codeUnit == _underscore; - -/// True if already escaped -bool _areCodeUnitsEscaped(List codeUnits) { - if (codeUnits.isNotEmpty) { - final first = codeUnits.first; - switch (first) { - case _doubleQuote: - case _backtick: - final last = codeUnits.last; - return last == first; - case _singleQuote: - // not yet - } - } - return false; -} - -bool _entityNameNeedEscape(String name) { - /// We need to escape if not escaped yet and if not a valid keyword - if (escapeNames.contains(name.toLowerCase())) { - return true; - } - - final codeUnits = name.codeUnits; - - // Must start with a alpha or underscode - if (!_isAlphaOrUnderscore(codeUnits.first)) { - return true; - } - for (var i = 1; i < codeUnits.length; i++) { - final codeUnit = codeUnits[i]; - if (!_isAlphaOrUnderscore(codeUnit) && !_isDigit(codeUnit)) { - return true; - } - } - - return false; -} - -/// Unescape a table or column name. -String unescapeValueKeyName(String name) { - final codeUnits = name.codeUnits; - if (_areCodeUnitsEscaped(codeUnits)) { - return name.substring(1, name.length - 1); - } - return name; -} - -/// SQLite keywords to escape. -/// -/// This list was built from the whole set of keywords -/// ([allKeywords] kept here for reference -/// ignore: prefer_collection_literals -final Set escapeNames = { - 'add', - 'all', - 'alter', - 'and', - 'as', - 'autoincrement', - 'between', - 'case', - 'check', - 'collate', - 'commit', - 'constraint', - 'create', - 'default', - 'deferrable', - 'delete', - 'distinct', - 'drop', - 'else', - 'escape', - 'except', - 'exists', - 'foreign', - 'from', - 'group', - 'having', - 'if', - 'in', - 'index', - 'insert', - 'intersect', - 'into', - 'is', - 'isnull', - 'join', - 'limit', - 'not', - 'notnull', - 'null', - 'on', - 'or', - 'order', - 'primary', - 'references', - 'select', - 'set', - 'table', - 'then', - 'to', - 'transaction', - 'union', - 'unique', - 'update', - 'using', - 'values', - 'when', - 'where' -}; - -/* -All keywords kept here for reference - -Set _allKeywords = new Set.from([ - 'abort', - 'action', - 'add', - 'after', - 'all', - 'alter', - 'analyze', - 'and', - 'as', - 'asc', - 'attach', - 'autoincrement', - 'before', - 'begin', - 'between', - 'by', - 'cascade', - 'case', - 'cast', - 'check', - 'collate', - 'column', - 'commit', - 'conflict', - 'constraint', - 'create', - 'cross', - 'current_date', - 'current_time', - 'current_timestamp', - 'database', - 'default', - 'deferrable', - 'deferred', - 'delete', - 'desc', - 'detach', - 'distinct', - 'drop', - 'each', - 'else', - 'end', - 'escape', - 'except', - 'exclusive', - 'exists', - 'explain', - 'fail', - 'for', - 'foreign', - 'from', - 'full', - 'glob', - 'group', - 'having', - 'if', - 'ignore', - 'immediate', - 'in', - 'index', - 'indexed', - 'initially', - 'inner', - 'insert', - 'instead', - 'intersect', - 'into', - 'is', - 'isnull', - 'join', - 'key', - 'left', - 'like', - 'limit', - 'match', - 'natural', - 'no', - 'not', - 'notnull', - 'null', - 'of', - 'offset', - 'on', - 'or', - 'order', - 'outer', - 'plan', - 'pragma', - 'primary', - 'query', - 'raise', - 'recursive', - 'references', - 'regexp', - 'reindex', - 'release', - 'rename', - 'replace', - 'restrict', - 'right', - 'rollback', - 'row', - 'savepoint', - 'select', - 'set', - 'table', - 'temp', - 'temporary', - 'then', - 'to', - 'transaction', - 'trigger', - 'union', - 'unique', - 'update', - 'using', - 'vacuum', - 'values', - 'view', - 'virtual', - 'when', - 'where', - 'with', - 'without' -]); -*/ diff --git a/sqflite/tripartite/sqflite_common/lib/src/sql_command.dart b/sqflite/tripartite/sqflite_common/lib/src/sql_command.dart deleted file mode 100644 index bf0945ce08fb8eda727de23b3eed4fc23657aef3..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/sql_command.dart +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/// Sql command type. -enum SqliteSqlCommandType { - /// such CREATE TABLE, DROP_INDEX, pragma - execute, - - /// Insert statement, - insert, - - /// Update statement. - update, - - /// Delete statement. - delete, - - /// Query statement (SELECTà - query, -} - -/// Sql command. internal only. -class SqfliteSqlCommand { - /// The command type. - final SqliteSqlCommandType type; - - /// The sql statement. - final String sql; - - /// The sql arguments. - final List? arguments; - - /// Sql command. - SqfliteSqlCommand(this.type, this.sql, this.arguments); -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/transaction.dart b/sqflite/tripartite/sqflite_common/lib/src/transaction.dart deleted file mode 100644 index 4576d1a10d54c38f414f15a1d0ee34b9dab21ce1..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/transaction.dart +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/batch.dart'; -import 'package:sqflite_common/src/constant.dart'; -import 'package:sqflite_common/src/database.dart'; -import 'package:sqflite_common/src/database_mixin.dart'; - -/// Transaction param, new in transaction v2 -class SqfliteTransactionParam { - /// null for no transaction - /// - final int? transactionId; - - /// Transaction param, new in transaction v2. - SqfliteTransactionParam(this.transactionId); -} - -/// Transaction mixin. -mixin SqfliteTransactionMixin implements Transaction { - /// Optional transaction id, depending on the implementation - int? transactionId; -} - -/// Transaction implementation -class SqfliteTransaction - with SqfliteDatabaseExecutorMixin, SqfliteTransactionMixin - implements Transaction { - /// Create a transaction on a given [database] - SqfliteTransaction(this.database); - - /// The transaction database - @override - final SqfliteDatabaseMixin database; - - @override - SqfliteDatabase get db => database; - - /// True if a transaction is successfull - bool? successful; - - @override - SqfliteTransaction get txn => this; - - @override - Batch batch() => SqfliteTransactionBatch(this); -} - -/// Special transaction that is run even if a pending transaction is in progress. -SqfliteTransaction getForcedSqfliteTransaction(SqfliteDatabaseMixin database) => - SqfliteTransaction(database)..transactionId = paramTransactionIdValueForce; diff --git a/sqflite/tripartite/sqflite_common/lib/src/utils.dart b/sqflite/tripartite/sqflite_common/lib/src/utils.dart deleted file mode 100644 index 87537ed1acbfde4c2c4cbb87aa0b067863c93e0a..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/utils.dart +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'constant.dart' as constant; - -/// Try to convert anything (int, String) to an int. -int? parseInt(Object? object) { - if (object is int) { - return object; - } else if (object is String) { - try { - return int.parse(object); - } catch (_) {} - } - return null; -} - -/// Debug mode activated -/// -/// To deprecated since 1.1.7 -bool debugModeOn = false; - -/// True if entering, false if leaving, null otherwise. -bool? getSqlInTransactionArgument(String sql) { - final lowerSql = sql.trim().toLowerCase(); - if (lowerSql.startsWith('begin')) { - return true; - } else if (lowerSql.startsWith('commit') || lowerSql.startsWith('rollback')) { - return false; - } - return null; -} - -/// Default duration before printing a lock warning if a database call hangs. -/// -/// Non final for changing it during testing. -/// -/// If a database called is delayed by this duration, a print will happen. -Duration? lockWarningDuration = constant.lockWarningDurationDefault; - -/// Default lock warning callback. -/// -/// Use [setLockWarningInfo] instead. -void Function()? lockWarningCallback = _lockWarningCallbackDefault; - -void _lockWarningCallbackDefault() { - print('Warning database has been locked for $lockWarningDuration. ' - 'Make sure you always use the transaction object for database operations during a transaction'); -} - -/// Split a list in sub list with a maximum size. -/// -/// Never returns list. if list is null, returns an empty list. -/// If [chunkSize] is null or 0, returns all in one list; -List> listChunk(List list, int? chunkSize) { - var chunks = >[]; - final len = list.length; - if ((chunkSize ?? 0) == 0) { - chunkSize = len; - } - for (var i = 0; i < len; i += chunkSize) { - final size = i + chunkSize!; - chunks.add(list.sublist(i, size > len ? len : size)); - } - - return chunks; -} diff --git a/sqflite/tripartite/sqflite_common/lib/src/value_utils.dart b/sqflite/tripartite/sqflite_common/lib/src/value_utils.dart deleted file mode 100644 index 28f0717f7736d89504cb3806441221dc9db6bcee..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/src/value_utils.dart +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'dart:typed_data'; - -import 'package:sqflite_common/src/env_utils.dart'; - -/// Don't throw exception yet. will be done in the future. -var checkThrowException = false; - -var _debugCheckPrinted = {}; - -void _checkArg(dynamic arg) { - if ((arg is! String) && (arg is! num) && (arg is! Uint8List)) { - // Big int ok on the web only - if (kSqfliteIsWeb) { - if (arg is BigInt) { - return; - } - } - final type = arg.runtimeType.toString(); - - final text = ''' -*** WARNING *** - -Invalid argument $arg with type $type. -Only num, String and Uint8List are supported. See https://github.com/tekartik/sqflite/blob/master/sqflite/doc/supported_types.md for details - -This will throw an exception in the future. For now it is displayed once per type. - - '''; - if (checkThrowException) { - throw ArgumentError(text); - } else { - final printed = _debugCheckPrinted[type] ?? false; - if (!printed) { - _debugCheckPrinted[type] = true; - print(text); - } - } - } -} - -/// Check the value is valid. test for non null only; -void checkNonNullValue(dynamic value) { - if (isDebug) { - _checkArg(value); - } -} - -/// Check whether the args are valid in raw statement. null is supported here -void checkRawArgs(List? args) { - if (isDebug && args != null) { - for (var arg in args) { - if (arg != null) { - _checkArg(arg); - } - } - } -} - -/// Check whether the where args are valid. null is not supported here. -void checkWhereArgs(List? args) { - if (isDebug && args != null) { - for (var arg in args) { - _checkArg(arg); - } - } -} diff --git a/sqflite/tripartite/sqflite_common/lib/utils/utils.dart b/sqflite/tripartite/sqflite_common/lib/utils/utils.dart deleted file mode 100644 index 4435036fa4b4e63a4a126096c1edbc7f038274ca..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/lib/utils/utils.dart +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -import 'package:sqflite_common/src/utils.dart'; -import 'package:sqflite_common/src/utils.dart' as impl; - -/// helper to get the first int value in a query -/// Useful for COUNT(*) queries -int? firstIntValue(List> list) { - if (list.isNotEmpty) { - final firstRow = list.first; - if (firstRow.isNotEmpty) { - return parseInt(firstRow.values.first); - } - } - return null; -} - -/// Utility to encode a blob to allow blob query using -/// 'hex(blob_field) = ?', Sqlite.hex([1,2,3]) -String hex(List bytes) { - final buffer = StringBuffer(); - for (var part in bytes) { - if (part & 0xff != part) { - throw FormatException('$part is not a byte integer'); - } - buffer.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}'); - } - return buffer.toString().toUpperCase(); -} - -/// Deprecated since 1.1.7+. -/// -/// Used internally. -@Deprecated('Used internally') -void Function()? get lockWarningCallback => impl.lockWarningCallback; - -/// Deprecated since 1.1.7+. -@Deprecated('Used internally') -set lockWarningCallback(void Function()? callback) => - impl.lockWarningCallback = callback; - -/// Deprecated since 1.1.7+. -@Deprecated('Used internally') -Duration? get lockWarningDuration => impl.lockWarningDuration; - -/// Deprecated since 1.1.7+. -@Deprecated('Used internally') -set lockWarningDuration(Duration? duration) => - impl.lockWarningDuration = duration; - -/// Change database lock behavior mechanism. -/// -/// Default behavior is to print a message if a command hangs for more than -/// 10 seconds. Set en empty callback (not null) to prevent it from being -/// displayed. -void setLockWarningInfo({Duration? duration, void Function()? callback}) { - impl.lockWarningDuration = duration ?? impl.lockWarningDuration; - impl.lockWarningCallback = callback ?? impl.lockWarningCallback; -} - -/// count column. -const sqlCountColumn = 'COUNT(*)'; diff --git a/sqflite/tripartite/sqflite_common/pubspec.yaml b/sqflite/tripartite/sqflite_common/pubspec.yaml deleted file mode 100644 index dd51c7433e9d44c07ecb12925d04618d43b59f50..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/pubspec.yaml +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -name: sqflite_common -homepage: https://github.com/tekartik/sqflite/tree/master/sqflite_common -description: Dart wrapper on SQLite, a self-contained, high-reliability, embedded, SQL database engine. -version: 2.4.5 -funding: - - https://github.com/sponsors/alextekartik - -environment: - sdk: '>=2.18.0 <4.0.0' - -dependencies: - synchronized: '>=3.0.0 <5.0.0' - path: '>=1.8.0 <3.0.0' - meta: '>=1.3.0 <3.0.0' - -dev_dependencies: - lints: '>=1.0.0' - process_run: '>=0.12.0' - http: '>=0.13.0' - test: '>=1.16.2' - test_api: '>=0.2.19' - pub_semver: '>=2.0.0' \ No newline at end of file diff --git a/sqflite/tripartite/sqflite_common/test/import_mixin_test.dart b/sqflite/tripartite/sqflite_common/test/import_mixin_test.dart deleted file mode 100644 index 07aa48c8520f738e7346d7b01be9e84a3b69b83f..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/import_mixin_test.dart +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/src/mixin/dev_utils.dart'; -import 'package:sqflite_common/src/mixin/import_mixin.dart'; -import 'package:test/test.dart'; - -void main() { - group('handler_mixin', () { - // Check that public api are exported - test('exported', () { - for (var value in [ - // ignore: deprecated_member_use_from_same_package - SqfliteOptions, - methodOpenDatabase, - methodOpenDatabase, - methodCloseDatabase, - methodOptions, - sqliteErrorCode, - methodInsert, - methodQuery, - methodUpdate, - methodExecute, - methodBatch, - // Factory - buildDatabaseFactory, SqfliteInvokeHandler, SqfliteDatabaseFactoryBase, - SqfliteDatabaseFactoryMixin, SqfliteDatabaseFactory, - // Database - SqfliteDatabaseOpenHelper, SqfliteDatabase, SqfliteDatabaseMixin, - SqfliteDatabaseBase, - // Exception - SqfliteDatabaseException, - // ignore: deprecated_member_use_from_same_package - devPrint, devWarning, - ]) { - expect(value, isNotNull); - } - }); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/list_mixin_test.dart b/sqflite/tripartite/sqflite_common/test/list_mixin_test.dart deleted file mode 100644 index 7c25689cbc4b934478d2672a13c3416f414ea0fc..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/list_mixin_test.dart +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'dart:collection'; - -import 'package:test/test.dart'; - -class MyList1 extends Object with ListMixin> { - MyList1.from(this._list); - - final List _list; - - @override - Map operator [](int index) { - final value = _list[index] as Map; - return value.cast(); - } - - @override - void operator []=(int index, Map value) { - throw 'read-only'; - } - - @override - set length(int newLength) { - throw 'read-only'; - } - - @override - int get length => _list.length; -} - -class MyList2 extends ListBase> { - MyList2.from(this._list); - - final List _list; - - @override - Map operator [](int index) { - final value = _list[index] as Map; - return value.cast(); - } - - @override - void operator []=(int index, Map value) { - throw 'read-only'; - } - - @override - set length(int newLength) { - throw 'read-only'; - } - - @override - int get length => _list.length; -} - -void main() { - group('mixin', () { - // This fails on beta 1, should work now - test('ListMixin', () { - final raw = [ - {'col': 1} - ]; - final rows = MyList1.from(raw); - expect(rows, raw); - }); - - test('ListBase', () { - final raw = [ - {'col': 1} - ]; - final rows = MyList2.from(raw); - expect(rows, raw); - }); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/path_utils_test.dart b/sqflite/tripartite/sqflite_common/test/path_utils_test.dart deleted file mode 100644 index 8b4851f3c09544533b89d1e1ad81b6854d7fd34a..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/path_utils_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/path_utils.dart'; -import 'package:test/test.dart'; - -void main() { - group('path_utils', () { - test('inMemory', () { - // Sounds obvious... - expect(inMemoryDatabasePath, ':memory:'); - expect(isInMemoryDatabasePath('test.db'), isFalse); - expect(isInMemoryDatabasePath(':memory:'), isTrue); - expect(isInMemoryDatabasePath('file::memory:'), isTrue); - }); - - test('fileUri', () { - expect(isFileUriDatabasePath('file::memory:'), isTrue); - expect(isFileUriDatabasePath('filememory'), isFalse); - expect(isFileUriDatabasePath('file:relative'), isTrue); - expect(isFileUriDatabasePath('file:///abs'), isTrue); - }); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/sqflite_batch_test.dart b/sqflite/tripartite/sqflite_common/test/sqflite_batch_test.dart deleted file mode 100644 index 68ff303f77e3948a3002e78ba28240a94071a8d7..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/sqflite_batch_test.dart +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:test/test.dart'; - -import 'test_scenario.dart'; - -void main() { - group('sqflite', () { - var startCommands = [protocolOpenStep]; - var endCommands = [protocolCloseStep]; - test('batch commit', () async { - final scenario = startScenario([ - ...startCommands, - [ - 'execute', - { - 'sql': 'BEGIN IMMEDIATE', - 'id': 1, - 'inTransaction': true, - 'transactionId': null - }, - null - ], - [ - 'batch', - { - 'operations': [ - {'method': 'execute', 'sql': 'PRAGMA dummy'} - ], - 'id': 1 - }, - null - ], - [ - 'execute', - {'sql': 'COMMIT', 'id': 1, 'inTransaction': false}, - null - ], - ...endCommands, - ]); - final factory = scenario.factory; - final db = await factory.openDatabase(inMemoryDatabasePath); - var batch = db.batch(); - expect(batch.length, 0); - batch.execute('PRAGMA dummy'); - expect(batch.length, 1); - expect(await batch.commit(), isEmpty); // Mock return values - await db.close(); - scenario.end(); - }); - test('batch apply', () async { - final scenario = startScenario([ - ...startCommands, - [ - 'batch', - { - 'operations': [ - {'method': 'execute', 'sql': 'PRAGMA dummy'} - ], - 'id': 1 - }, - null - ], - ...endCommands, - ]); - final factory = scenario.factory; - final db = await factory.openDatabase(inMemoryDatabasePath); - var batch = db.batch(); - batch.execute('PRAGMA dummy'); - await batch.apply(); - await db.close(); - scenario.end(); - }); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/sqflite_debug_test.dart b/sqflite/tripartite/sqflite_common/test/sqflite_debug_test.dart deleted file mode 100644 index 0827236a9d333ba4c8803dd7645da2d8aa071a83..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/sqflite_debug_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/constant.dart'; -import 'package:sqflite_common/src/method_call.dart'; -import 'package:sqflite_common/src/mixin/factory.dart'; -import 'package:test/test.dart'; - -var logs = []; -var databaseFactoryMock = buildDatabaseFactory( - tag: 'mock', - invokeMethod: (method, [arguments]) async { - logs.add(SqfliteMethodCall(method, arguments)); - if (method == methodGetDatabasesPath) { - return 'mock_path'; - } - }); - -void main() { - test('simple sqflite example', () async { - logs.clear(); - // ignore: deprecated_member_use_from_same_package - await databaseFactoryMock.debugSetLogLevel(sqfliteLogLevelVerbose); - expect(logs.map((log) => log.toMap()), [ - { - 'method': 'options', - 'arguments': {'logLevel': 2} - } - ]); - }); - test('databasesPath', () async { - final oldDatabasePath = await databaseFactoryMock.getDatabasesPath(); - try { - await databaseFactoryMock.setDatabasesPath('.'); - final path = await databaseFactoryMock.getDatabasesPath(); - expect(path, '.'); - } finally { - await databaseFactoryMock.setDatabasesPath(oldDatabasePath); - } - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/sqflite_dev_test.dart b/sqflite/tripartite/sqflite_common/test/sqflite_dev_test.dart deleted file mode 100644 index 96b5a5570a24f018cd21f61de22b43f79f566781..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/sqflite_dev_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqflite_dev.dart'; -import 'package:sqflite_common/src/constant.dart'; -import 'package:sqflite_common/src/method_call.dart'; -import 'package:sqflite_common/src/mixin/factory.dart'; -import 'package:test/test.dart'; - -var logs = []; -var databaseFactoryMock = buildDatabaseFactory( - tag: 'mock', - invokeMethod: (method, [arguments]) async { - logs.add(SqfliteMethodCall(method, arguments)); - if (method == methodGetDatabasesPath) { - return 'mock_path'; - } - }); - -void main() { - test('simple sqflite example', () async { - logs.clear(); - // ignore: deprecated_member_use_from_same_package - await databaseFactoryMock.setLogLevel(sqfliteLogLevelVerbose); - expect(logs.map((log) => log.toMap()), [ - { - 'method': 'options', - 'arguments': {'logLevel': 2} - } - ]); - }); - test('databasesPath', () async { - final oldDatabasePath = await databaseFactoryMock.getDatabasesPath(); - try { - await databaseFactoryMock.setDatabasesPath('.'); - final path = await databaseFactoryMock.getDatabasesPath(); - expect(path, '.'); - } finally { - await databaseFactoryMock.setDatabasesPath(oldDatabasePath); - } - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/sqflite_exception_test.dart b/sqflite/tripartite/sqflite_common/test/sqflite_exception_test.dart deleted file mode 100644 index 5c45af6b314b172b1229dc1ecda01399def1e88d..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/sqflite_exception_test.dart +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'dart:typed_data'; - -import 'package:sqflite_common/src/exception.dart'; -import 'package:test/test.dart'; - -void main() { - group('sqflite_exception', () { - test('isUniqueConstraint', () async { - // Android - var msg = 'UNIQUE constraint failed: Test.name (code 2067))'; - var exception = SqfliteDatabaseException(msg, null); - expect(exception.isDatabaseClosedError(), isFalse); - expect(exception.isReadOnlyError(), isFalse); - expect(exception.isNoSuchTableError(), isFalse); - expect(exception.isOpenFailedError(), isFalse); - expect(exception.isSyntaxError(), isFalse); - expect(exception.isNotNullConstraintError(), isFalse); - expect(exception.isUniqueConstraintError(), isTrue); - expect(exception.isUniqueConstraintError('Test.name'), isTrue); - - msg = 'UNIQUE constraint failed: Test.name (code 1555))'; - exception = SqfliteDatabaseException(msg, null); - expect(exception.isSyntaxError(), isFalse); - expect(exception.isUniqueConstraintError(), isTrue); - expect(exception.isUniqueConstraintError('Test.name'), isTrue); - }); - - test('isNotNullConstraint', () async { - // FFI mac - var msg = - 'DatabaseException(SqliteException(1299): NOT NULL constraint failed: Test.name, constraint failed (code 1299))'; - var exception = SqfliteDatabaseException(msg, null); - expect(exception.isDatabaseClosedError(), isFalse); - expect(exception.isReadOnlyError(), isFalse); - expect(exception.isNoSuchTableError(), isFalse); - expect(exception.isOpenFailedError(), isFalse); - expect(exception.isSyntaxError(), isFalse); - expect(exception.isUniqueConstraintError(), isFalse); - expect(exception.isUniqueConstraintError('Test.name'), isFalse); - expect(exception.getResultCode(), 1299); - - // ios - msg = - 'DatabaseException(Error Domain=FMDatabase Code=1299 "NOT NULL constraint failed: Test.name"'; - exception = SqfliteDatabaseException(msg, null); - expect(exception.isSyntaxError(), isFalse); - expect(exception.isNotNullConstraintError(), isTrue); - expect(exception.isNotNullConstraintError('Test.name'), isTrue); - expect(exception.isUniqueConstraintError(), isFalse); - expect(exception.isUniqueConstraintError('Test.name'), isFalse); - expect(exception.getResultCode(), 1299); - }); - - test('isSyntaxError', () async { - // Android - final msg = 'near "DUMMY": syntax error (code 1)'; - final exception = SqfliteDatabaseException(msg, null); - expect(exception.isDatabaseClosedError(), isFalse); - expect(exception.isReadOnlyError(), isFalse); - expect(exception.isNoSuchTableError(), isFalse); - expect(exception.isOpenFailedError(), isFalse); - expect(exception.isSyntaxError(), isTrue); - expect(exception.isUniqueConstraintError(), isFalse); - expect(exception.getResultCode(), 1); - }); - - test('isSyntaxError with symbolic names', () { - // Android - final msg = 'near "DUMMY": syntax error (code 1 SQLITE_ERROR)'; - final exception = SqfliteDatabaseException(msg, null); - expect(exception.isDatabaseClosedError(), isFalse); - expect(exception.isReadOnlyError(), isFalse); - expect(exception.isNoSuchTableError(), isFalse); - expect(exception.isOpenFailedError(), isFalse); - expect(exception.isSyntaxError(), isTrue); - expect(exception.isUniqueConstraintError(), isFalse); - expect(exception.getResultCode(), 1); - }); - - test('isNoSuchTable', () async { - // Android - final msg = 'no such table: Test (code 1)'; - final exception = SqfliteDatabaseException(msg, null); - expect(exception.isDatabaseClosedError(), isFalse); - expect(exception.isReadOnlyError(), isFalse); - expect(exception.isNoSuchTableError(), isTrue); - expect(exception.isNoSuchTableError('Test'), isTrue); - expect(exception.isNoSuchTableError('Other'), isFalse); - expect(exception.isDuplicateColumnError('tableName'), isFalse); - expect(exception.isDuplicateColumnError(), isFalse); - expect(exception.isOpenFailedError(), isFalse); - expect(exception.isSyntaxError(), isFalse); - expect(exception.isUniqueConstraintError(), isFalse); - expect(exception.getResultCode(), 1); - }); - - test('isDuplicateColumn', () { - // Android - final msg = 'duplicate column name: tableName (code 1 SQLITE_ERROR)'; - final exception = SqfliteDatabaseException(msg, null); - expect(exception.isDatabaseClosedError(), isFalse); - expect(exception.isReadOnlyError(), isFalse); - expect(exception.isDuplicateColumnError('tableName'), isTrue); - expect(exception.isDuplicateColumnError(), isTrue); - expect(exception.isDuplicateColumnError('tableName2'), isFalse); - expect(exception.isNoSuchTableError(), isFalse); - expect(exception.isNoSuchTableError('Test'), isFalse); - expect(exception.isNoSuchTableError('Other'), isFalse); - expect(exception.isOpenFailedError(), isFalse); - expect(exception.isSyntaxError(), isFalse); - expect(exception.isUniqueConstraintError(), isFalse); - expect(exception.getResultCode(), 1); - }); - test('getResultCode', () async { - // Android - final msg = 'UNIQUE constraint failed: Test.name (code 2067))'; - var exception = SqfliteDatabaseException(msg, null); - expect(exception.getResultCode(), 2067); - exception = SqfliteDatabaseException( - 'UNIQUE constraint failed: Test.name (code 1555))', null); - expect(exception.getResultCode(), 1555); - exception = - SqfliteDatabaseException('near "DUMMY": syntax error (code 1)', null); - expect(exception.getResultCode(), 1); - - exception = SqfliteDatabaseException( - 'attempt to write a readonly database (code 8)) running Open read-only', - null); - expect(exception.getResultCode(), 8); - - // iOS: Error Domain=FMDatabase Code=19 'UNIQUE constraint failed: Test.name' UserInfo={NSLocalizedDescription=UNIQUE constraint failed: Test.name}) s - exception = SqfliteDatabaseException( - "Error Domain=FMDatabase Code=19 'UNIQUE constraint failed: Test.name' UserInfo={NSLocalizedDescription=UNIQUE constraint failed: Test.name})", - null); - expect(exception.getResultCode(), 19); - exception = - SqfliteDatabaseException('Error Domain=FMDatabase Code=19', null); - expect(exception.getResultCode(), 19); - }); - - test('Exception args', () async { - var exception = SqfliteDatabaseException('test', { - 'sql': 'statement', - 'arguments': [ - null, - 1, - 'short', - '123456789012345678901234567890123456789012345678901', - Uint8List.fromList([1, 2, 3]) - ] - }); - expect(exception.toString(), - 'DatabaseException(test) sql \'statement\' args [null, 1, short, 12345678901234567890123456789012345678901234567890..., Blob(3)]'); - }); - test('Exception result', () async { - DatabaseException exception = SqfliteDatabaseException('test', 1); - expect(exception.result, 1); - exception = SqfliteDatabaseException('test', null); - expect(exception.result, isNull); - }); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/sqflite_impl_test.dart b/sqflite/tripartite/sqflite_common/test/sqflite_impl_test.dart deleted file mode 100644 index e13049619b7a522586fdbf6c985e0350612a456f..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/sqflite_impl_test.dart +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/src/collection_utils.dart'; -import 'package:sqflite_common/src/exception.dart'; -import 'package:test/test.dart'; - -void main() { - group('sqflite', () { - test('Rows', () { - final raw = [ - {'col': 1} - ]; - final rows = Rows.from(raw); - final row = rows.first; - expect(rows, raw); - expect(row, {'col': 1}); - }); - - test('fromRawOperationResult', () async { - expect(fromRawOperationResult({'result': 1}), 1); - expect( - fromRawOperationResult({ - 'result': { - 'columns': ['column'], - 'rows': [ - [1] - ] - } - }), - >[ - {'column': 1} - ]); - var exception = fromRawOperationResult({ - 'error': { - 'code': 1234, - 'message': 'hello', - 'data': {'some': 'data'} - } - }) as SqfliteDatabaseException; - expect(exception.message, 'hello'); - expect(exception.result, {'some': 'data'}); - expect(exception.getResultCode(), null); - - exception = fromRawOperationResult({ - 'error': { - 'code': 1234, - 'message': 'hello', - 'data': {'some': 'data'}, - 'resultCode': 1, - } - }) as SqfliteDatabaseException; - expect(exception.message, 'hello'); - expect(exception.result, {'some': 'data'}); - expect(exception.getResultCode(), 1); - }); - test('ResultSet', () { - final raw = { - 'columns': ['column'], - 'rows': [ - [1] - ] - }; - final queryResultSet = QueryResultSet([ - 'column' - ], [ - [1] - ]); - expect(queryResultSet.columnIndex('dummy'), isNull); - expect(queryResultSet.columnIndex('column'), 0); - final row = queryResultSet.first; - //expect(rows, raw); - expect(row, {'column': 1}); - - // read only - try { - row['column'] = 2; - fail('should have failed'); - } on UnsupportedError catch (_) {} - final map = Map.from(row); - // now can modify - map['column'] = 2; - - final queryResultSetMap = { - 'columns': ['id', 'name'], - 'rows': >[ - [1, 'item 1'], - [2, 'item 2'] - ] - }; - final expected = >[ - {'id': 1, 'name': 'item 1'}, - {'id': 2, 'name': 'item 2'} - ]; - expect(queryResultToList(queryResultSetMap), expected); - expect(queryResultToList(expected), expected); - expect(queryResultToList(raw), >[ - {'column': 1} - ]); - - expect(queryResultToList({}), []); - }); - - test('duplicated key', () { - final queryResultSet = QueryResultSet([ - 'col', - 'col' - ], [ - [1, 2] - ]); - // last one wins... - expect(queryResultSet.columnIndex('col'), 1); - final row = queryResultSet.first; - expect(row['col'], 2); - - expect(row.length, 1); - expect(row.keys, ['col']); - expect(row.values, [2]); - expect(row, {'col': 2}); - }); - - test('lockWarning', () {}); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/sqflite_logger_test.dart b/sqflite/tripartite/sqflite_common/test/sqflite_logger_test.dart deleted file mode 100644 index 091fd10726822791a23e924be2d007ca64842b22..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/sqflite_logger_test.dart +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/internals.dart'; -import 'package:sqflite_common/src/logger/sqflite_logger.dart'; -import 'package:test/test.dart'; - -import 'src_mixin_test.dart'; - -void main() { - group('sqflite_logger', () { - test('invoke', () async { - var events = []; - var lines = []; - final factory = SqfliteDatabaseFactoryLogger(MockDatabaseFactoryEmpty(), - options: SqfliteLoggerOptions( - type: SqfliteDatabaseFactoryLoggerType.invoke, - log: (event) { - event.dump( - print: (msg) { - lines.add(msg?.toString() ?? ''); - print(msg); - }, - noStopwatch: true); - events.add(event); - })); - try { - await factory.internalsInvokeMethod('test', {'some': 'param'}); - } catch (_) { - // unimplemented - } - var event = events.first as SqfliteLoggerInvokeEvent; - expect(event.method, 'test'); - expect(event.arguments, {'some': 'param'}); - expect(event.sw!.isRunning, isFalse); - // is currently an error - // 'invoke:({method: test, arguments: {some: param}, error: UnimplementedError: test {some: param}})' - expect(lines.first, - startsWith('invoke:({method: test, arguments: {some: param}')); - }); - test('all', () async { - var events = []; - var lines = []; - final factory = SqfliteDatabaseFactoryLogger(MockDatabaseFactoryEmpty(), - options: SqfliteLoggerOptions( - type: SqfliteDatabaseFactoryLoggerType.all, - log: (event) { - event.dump( - print: (msg) { - lines.add(msg?.toString() ?? ''); - print(msg); - }, - noStopwatch: true); - events.add(event); - })); - var db = await factory.openDatabase(inMemoryDatabasePath); - var batch = db.batch(); - batch.rawQuery('PRAGMA user_version'); - await batch.commit(); - var event = events.first as SqfliteLoggerDatabaseOpenEvent; - expect(event.path, inMemoryDatabasePath); - expect(event.options?.readOnly, false); - expect(event.sw!.isRunning, isFalse); - await db.close(); - expect(lines, [ - 'openDatabase:({path: :memory:, options: {readOnly: false, singleInstance: true}})', - 'execute:({db: 1, sql: BEGIN IMMEDIATE})', - 'batch:({db: 1})', - ' query({sql: PRAGMA user_version})', - 'execute:({db: 1, sql: COMMIT})', - 'closeDatabase:({db: 1})' - ]); - }); - test('batch', () async {}); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/sqflite_not_initialized_test.dart b/sqflite/tripartite/sqflite_common/test/sqflite_not_initialized_test.dart deleted file mode 100644 index dae6d44fbf7a6567fb602854f8aaa90f6637028e..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/sqflite_not_initialized_test.dart +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqflite.dart'; -import 'package:test/test.dart'; - -void main() { - test('basic', () async { - await expectLater( - () => openDatabase(inMemoryDatabasePath), throwsA(isA())); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/sqflite_open_test.dart b/sqflite/tripartite/sqflite_common/test/sqflite_open_test.dart deleted file mode 100644 index d517d21636dd39c64af56b5a9fd838cf3f366c43..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/sqflite_open_test.dart +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:test/test.dart'; - -import 'test_scenario.dart'; - -void main() { - group('sqflite', () { - test('open id result compat', () async { - final scenario = startScenario([ - [ - 'openDatabase', - {'path': ':memory:', 'singleInstance': false}, - 1 - ], - [ - 'closeDatabase', - {'id': 1}, - null - ], - ]); - final factory = scenario.factory; - final db = await factory.openDatabase(inMemoryDatabasePath); - await db.close(); - scenario.end(); - }); - test('open map result', () async { - final scenario = startScenario([ - [ - 'openDatabase', - {'path': ':memory:', 'singleInstance': false}, - {'id': 1}, - ], - [ - 'closeDatabase', - {'id': 1}, - null - ], - ]); - final factory = scenario.factory; - final db = await factory.openDatabase(inMemoryDatabasePath); - await db.close(); - scenario.end(); - }); - test('open with version', () async { - final scenario = startScenario([ - protocolOpenStep, - [ - 'query', - {'sql': 'PRAGMA user_version', 'id': 1}, - // ignore: inference_failure_on_collection_literal - {} - ], - [ - 'execute', - { - 'sql': 'BEGIN EXCLUSIVE', - 'id': 1, - 'inTransaction': true, - 'transactionId': null - }, - null - ], - [ - 'query', - {'sql': 'PRAGMA user_version', 'id': 1}, - // ignore: inference_failure_on_collection_literal - {} - ], - [ - 'execute', - {'sql': 'PRAGMA user_version = 1', 'id': 1}, - null - ], - [ - 'execute', - {'sql': 'COMMIT', 'id': 1, 'inTransaction': false}, - null - ], - protocolCloseStep, - ]); - final db = await scenario.factory.openDatabase(inMemoryDatabasePath, - options: OpenDatabaseOptions(version: 1, onCreate: (db, version) {})); - await db.close(); - scenario.end(); - }); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/sqflite_sql_test.dart b/sqflite/tripartite/sqflite_common/test/sqflite_sql_test.dart deleted file mode 100644 index 50cd0a3b59f8e0570191d3d6ab1faf1cc802eccd..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/sqflite_sql_test.dart +++ /dev/null @@ -1,313 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'dart:typed_data'; - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:test/test.dart'; - -import 'test_scenario.dart'; - -void main() { - group('sqflite', () { - test('open execute', () async { - final scenario = startScenario([ - protocolOpenStep, - [ - 'execute', - {'sql': 'PRAGMA user_version = 1', 'id': 1}, - null, - ], - protocolCloseStep - ]); - final db = await scenario.factory.openDatabase(inMemoryDatabasePath); - await db.setVersion(1); - - await db.close(); - scenario.end(); - }); - test('transaction v2', () async { - final scenario = startScenario([ - protocolOpenStep, - [ - 'execute', - { - 'sql': 'BEGIN IMMEDIATE', - 'id': 1, - 'inTransaction': true, - 'transactionId': null - }, - {'transactionId': 1}, - ], - [ - 'execute', - { - 'sql': 'COMMIT', - 'id': 1, - 'inTransaction': false, - 'transactionId': 1 - }, - null, - ], - protocolCloseStep - ]); - final db = await scenario.factory.openDatabase(inMemoryDatabasePath); - await db.transaction((txn) async {}); - - await db.close(); - scenario.end(); - }); - - test('transaction v1', () async { - final scenario = startScenario([ - protocolOpenStep, - [ - 'execute', - { - 'sql': 'BEGIN IMMEDIATE', - 'id': 1, - 'inTransaction': true, - 'transactionId': null - }, - null, - ], - [ - 'execute', - { - 'sql': 'COMMIT', - 'id': 1, - 'inTransaction': false, - }, - null, - ], - protocolCloseStep - ]); - final db = await scenario.factory.openDatabase(inMemoryDatabasePath); - await db.transaction((txn) async {}); - - await db.close(); - scenario.end(); - }); - - test('manual begin transaction', () async { - final scenario = startScenario([ - protocolOpenStep, - [ - 'execute', - {'sql': 'BEGIN TRANSACTION', 'id': 1, 'inTransaction': true}, - null, - ], - [ - 'execute', - { - 'sql': 'ROLLBACK', - 'id': 1, - 'inTransaction': false, - 'transactionId': -1 - }, - null, - ], - protocolCloseStep - ]); - final db = await scenario.factory.openDatabase(inMemoryDatabasePath); - await db.execute('BEGIN TRANSACTION'); - - await db.close(); - scenario.end(); - }); - - test('manual begin end transaction', () async { - final scenario = startScenario([ - protocolOpenStep, - [ - 'execute', - {'sql': 'BEGIN TRANSACTION', 'id': 1, 'inTransaction': true}, - null, - ], - [ - 'execute', - {'sql': 'ROLLBACK TRANSACTION', 'id': 1, 'inTransaction': false}, - null, - ], - protocolCloseStep - ]); - final db = await scenario.factory.openDatabase(inMemoryDatabasePath); - await db.execute('BEGIN TRANSACTION'); - await db.execute('ROLLBACK TRANSACTION'); - - await db.close(); - scenario.end(); - }); - test('open insert', () async { - final scenario = startScenario([ - protocolOpenStep, - [ - 'insert', - { - 'sql': 'INSERT INTO test (blob) VALUES (?)', - 'arguments': [ - [1, 2, 3] - ], - 'id': 1 - }, - 1 - ], - protocolCloseStep - ]); - final db = await scenario.factory.openDatabase(inMemoryDatabasePath); - expect( - await db.insert('test', { - 'blob': Uint8List.fromList([1, 2, 3]) - }), - 1); - await db.close(); - scenario.end(); - }); - - test('open insert conflict', () async { - final scenario = startScenario([ - protocolOpenStep, - [ - 'insert', - { - 'sql': 'INSERT OR IGNORE INTO test (value) VALUES (?)', - 'arguments': [1], - 'id': 1 - }, - 1 - ], - protocolCloseStep - ]); - final db = await scenario.factory.openDatabase(inMemoryDatabasePath); - expect( - await db.insert('test', {'value': 1}, - conflictAlgorithm: ConflictAlgorithm.ignore), - 1); - await db.close(); - scenario.end(); - }); - - test('open batch insert', () async { - final scenario = startScenario([ - protocolOpenStep, - [ - 'execute', - { - 'sql': 'BEGIN IMMEDIATE', - 'id': 1, - 'inTransaction': true, - 'transactionId': null, - }, - {'transactionId': 1} - ], - [ - 'batch', - { - 'operations': [ - { - 'method': 'insert', - 'sql': 'INSERT INTO test (blob) VALUES (?)', - 'arguments': [ - [1, 2, 3] - ] - } - ], - 'id': 1, - 'transactionId': 1 - }, - null - ], - [ - 'execute', - { - 'sql': 'COMMIT', - 'id': 1, - 'inTransaction': false, - 'transactionId': 1 - }, - null - ], - protocolCloseStep - ]); - final db = await scenario.factory.openDatabase(inMemoryDatabasePath); - final batch = db.batch(); - batch.insert('test', { - 'blob': Uint8List.fromList([1, 2, 3]) - }); - await batch.commit(); - await db.close(); - scenario.end(); - }); - - test('queryCursor', () async { - final scenario = startScenario([ - protocolOpenStep, - [ - 'query', - { - 'sql': '_', - 'id': 1, - 'cursorPageSize': 2, - }, - { - 'cursorId': 1, - 'rows': [ - // ignore: inference_failure_on_collection_literal - [{}] - ], - // ignore: inference_failure_on_collection_literal - 'columns': [] - } - ], - [ - 'queryCursorNext', - {'cursorId': 1, 'id': 1}, - { - 'cursorId': 1, - 'rows': [ - // ignore: inference_failure_on_collection_literal - [{}] - ], - // ignore: inference_failure_on_collection_literal - 'columns': [] - }, - ], - [ - 'queryCursorNext', - {'cursorId': 1, 'cancel': true, 'id': 1}, - null - ], - protocolCloseStep - ]); - var resultList = >[]; - final db = await scenario.factory.openDatabase(inMemoryDatabasePath); - var cursor = await db.rawQueryCursor( - '_', - null, - bufferSize: 2, - ); - expect(await cursor.moveNext(), isTrue); - resultList.add(cursor.current); - expect(await cursor.moveNext(), isTrue); - resultList.add(cursor.current); - await cursor.close(); - - // ignore: inference_failure_on_collection_literal - expect(resultList, [{}, {}]); - await db.close(); - scenario.end(); - }); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/sqflite_transaction_test.dart b/sqflite/tripartite/sqflite_common/test/sqflite_transaction_test.dart deleted file mode 100644 index 0b8c4627c089a837a4aaf146546ded86c9f02e8a..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/sqflite_transaction_test.dart +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/exception.dart'; -import 'package:test/test.dart'; - -import 'test_scenario.dart'; - -void main() { - group('transaction', () { - final transactionBeginStep = [ - 'execute', - { - 'sql': 'BEGIN IMMEDIATE', - 'id': 1, - 'inTransaction': true, - 'transactionId': null - }, - null, - ]; - final transactionBeginFailureStep = [ - 'execute', - { - 'sql': 'BEGIN IMMEDIATE', - 'id': 1, - 'inTransaction': true, - 'transactionId': null - }, - SqfliteDatabaseException('failure', null), - ]; - final transactionEndStep = [ - 'execute', - {'sql': 'COMMIT', 'id': 1, 'inTransaction': false}, - 1 - ]; - test('basic', () async { - final scenario = startScenario([ - protocolOpenStep, - transactionBeginStep, - transactionEndStep, - transactionBeginStep, - transactionEndStep, - protocolCloseStep, - ]); - final factory = scenario.factory; - final db = await factory.openDatabase(inMemoryDatabasePath); - - await db.transaction((txn) async {}); - await db.transaction((txn) async {}); - await db.close(); - scenario.end(); - }); - test('error in begin after open', () async { - final scenario = startScenario([ - protocolOpenStep, - transactionBeginFailureStep, - transactionBeginStep, - transactionEndStep, - protocolCloseStep, - ]); - final factory = scenario.factory; - final db = await factory.openDatabase(inMemoryDatabasePath); - - try { - await db.transaction((txn) async {}); - fail('should fail'); - } on DatabaseException catch (_) {} - await db.transaction((txn) async {}); - await db.close(); - scenario.end(); - }); - test('error in begin during open', () async { - final scenario = startScenario([ - protocolOpenStep, - [ - 'query', - {'sql': 'PRAGMA user_version', 'id': 1}, - // ignore: inference_failure_on_collection_literal - {}, - ], - [ - 'execute', - { - 'sql': 'BEGIN EXCLUSIVE', - 'id': 1, - 'inTransaction': true, - 'transactionId': null - }, - SqfliteDatabaseException('failure', null), - ], - [ - 'execute', - { - 'sql': 'ROLLBACK', - 'id': 1, - 'transactionId': -1, - 'inTransaction': false - }, - null, - ], - protocolCloseStep, - ]); - final factory = scenario.factory; - try { - await factory.openDatabase(inMemoryDatabasePath, - options: - OpenDatabaseOptions(version: 1, onCreate: (db, version) {})); - } on DatabaseException catch (_) {} - scenario.end(); - }); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/sql_builder_test.dart b/sqflite/tripartite/sqflite_common/test/sql_builder_test.dart deleted file mode 100644 index 9449a630ddfbfe6200191270b01af3e75abd3789..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/sql_builder_test.dart +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -//import 'package:test/test.dart'; -import 'package:sqflite_common/src/sql_builder.dart'; -import 'package:test/test.dart'; - -void main() { - group('sql_builder', () { - test('delete', () { - var builder = - SqlBuilder.delete('test', where: 'value = ?', whereArgs: [1]); - expect(builder.sql, 'DELETE FROM test WHERE value = ?'); - expect(builder.arguments, [1]); - - builder = SqlBuilder.delete('test'); - expect(builder.sql, 'DELETE FROM test'); - expect(builder.arguments, isNull); - - // escape - builder = SqlBuilder.delete('table'); - expect(builder.sql, 'DELETE FROM "table"'); - expect(builder.arguments, isNull); - }); - - test('query', () { - var builder = SqlBuilder.query('test'); - expect(builder.sql, 'SELECT * FROM test'); - expect(builder.arguments, isNull); - - builder = SqlBuilder.query('test', columns: ['COUNT(*)']); - expect(builder.sql, 'SELECT COUNT(*) FROM test'); - expect(builder.arguments, isNull); - - builder = SqlBuilder.query('test', - distinct: true, - columns: ['value'], - where: 'value = ?', - whereArgs: [1], - groupBy: 'group_value', - having: 'value > 0', - orderBy: 'other_value', - limit: 2, - offset: 3); - expect(builder.sql, - 'SELECT DISTINCT value FROM test WHERE value = ? GROUP BY group_value HAVING value > 0 ORDER BY other_value LIMIT 2 OFFSET 3'); - expect(builder.arguments, [1]); - }); - - test('insert', () { - try { - SqlBuilder.insert('test', {}); - fail('should fail, no nullColumnHack'); - } on ArgumentError catch (_) {} - - var builder = SqlBuilder.insert('test', {}, - nullColumnHack: 'value'); - expect(builder.sql, 'INSERT INTO test (value) VALUES (NULL)'); - expect(builder.arguments, isNull); - - builder = SqlBuilder.insert('test', {'value': 1}); - expect(builder.sql, 'INSERT INTO test (value) VALUES (?)'); - expect(builder.arguments, [1]); - - builder = SqlBuilder.insert( - 'test', {'value': 1, 'other_value': null}); - expect(builder.sql, - 'INSERT INTO test (value, other_value) VALUES (?, NULL)'); - expect(builder.arguments, [1]); - - builder = SqlBuilder.insert('test', {'value': 1}, - conflictAlgorithm: ConflictAlgorithm.ignore); - expect(builder.sql, 'INSERT OR IGNORE INTO test (value) VALUES (?)'); - expect(builder.arguments, [1]); - - // no escape yet - builder = SqlBuilder.insert('test', {'value:': 1}); - expect(builder.sql, 'INSERT INTO test (value:) VALUES (?)'); - expect(builder.arguments, [1]); - - // escape - builder = SqlBuilder.insert('table', {'table': 1}); - expect(builder.sql, 'INSERT INTO "table" ("table") VALUES (?)'); - expect(builder.arguments, [1]); - }); - - test('update', () { - try { - SqlBuilder.update('test', {}); - fail('should fail, no values'); - } on ArgumentError catch (_) {} - - var builder = SqlBuilder.update('test', {'value': 1}); - expect(builder.sql, 'UPDATE test SET value = ?'); - expect(builder.arguments, [1]); - - builder = SqlBuilder.update( - 'test', {'value': 1, 'other_value': null}); - expect(builder.sql, 'UPDATE test SET value = ?, other_value = NULL'); - expect(builder.arguments, [1]); - - // testing where - builder = SqlBuilder.update('test', {'value': 1}, - where: 'a = ? AND b = ?', whereArgs: ['some_test', 1]); - expect(builder.arguments, [1, 'some_test', 1]); - - // no escape yet - builder = SqlBuilder.update('test:', {'value:': 1}); - expect(builder.sql, 'UPDATE test: SET value: = ?'); - expect(builder.arguments, [1]); - - // escape - builder = SqlBuilder.update('test:', {'table': 1}); - expect(builder.sql, 'UPDATE test: SET "table" = ?'); - expect(builder.arguments, [1]); - }); - - test('query', () { - var builder = SqlBuilder.query('table', orderBy: 'value'); - expect(builder.sql, 'SELECT * FROM "table" ORDER BY value'); - expect(builder.arguments, isNull); - - builder = - SqlBuilder.query('table', orderBy: 'column_1 ASC, column_2 DESC'); - expect(builder.sql, - 'SELECT * FROM "table" ORDER BY column_1 ASC, column_2 DESC'); - expect(builder.arguments, isNull); - - // testing where - builder = SqlBuilder.query('test', - where: 'a = ? AND b = ?', whereArgs: ['some_test', 1]); - expect(builder.arguments, ['some_test', 1]); - }); - - test('isEscapedName', () { - //expect(isEscapedName(null), false); - expect(isEscapedName('group'), false); - expect(isEscapedName("'group'"), false); - expect(isEscapedName('"group"'), true); - expect(isEscapedName('`group`'), true); - expect(isEscapedName("`group'"), false); - expect(isEscapedName('"group"'), true); - }); - - test('escapeName', () { - // expect(escapeName(null!), null); - expect(escapeName('group'), '"group"'); - expect(escapeName('dummy'), 'dummy'); - expect(escapeName('"dummy"'), '"dummy"'); - expect(escapeName('semicolumn:'), 'semicolumn:'); // for now no escape - expect( - escapeName( - 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789'), - 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789'); - - for (var name in escapeNames) { - expect(escapeName(name), '"$name"'); - } - }); - - test('escapeEntityName', () { - // expect(escapeEntityName(null!), null); - expect(escapeEntityName('group'), '"group"'); - expect(escapeEntityName('dummy'), 'dummy'); - expect(escapeEntityName('"dummy"'), '""dummy""'); - expect(escapeEntityName('semicolumn:'), '"semicolumn:"'); - expect( - escapeEntityName( - 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789'), - 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789'); - - for (var name in escapeNames) { - expect(escapeEntityName(name), '"$name"'); - } - }); - - test('unescapeName', () { - // expect(unescapeName(null!), null); - - expect(unescapeName('dummy'), 'dummy'); - expect(unescapeName("'dummy'"), "'dummy'"); - expect(unescapeName("'group'"), "'group'"); - expect(unescapeName('"group"'), 'group'); - expect(unescapeName('`group`'), 'group'); - - for (var name in escapeNames) { - expect(unescapeName('"$name"'), name); - } - }); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/sql_test.dart b/sqflite/tripartite/sqflite_common/test/sql_test.dart deleted file mode 100644 index ee9e8aa07532683d99d7c4a6783cd28a44034bde..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/sql_test.dart +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sql.dart'; -import 'package:test/test.dart'; - -void main() { - group('sqflite', () { - test('exported', () { - expect(ConflictAlgorithm.abort, isNotNull); - }); - - test('escapeName_export', () { - expect(escapeName('group'), '"group"'); - }); - - test('unescapeName_export', () { - expect(unescapeName('"group"'), 'group'); - }); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/sqlite_api_test.dart b/sqflite/tripartite/sqflite_common/test/sqlite_api_test.dart deleted file mode 100644 index c0700eb31ec606f65daa0176ca8d18bd7165f888..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/sqlite_api_test.dart +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:test/test.dart'; - -void main() { - group('sqlite_api', () { - // Check that public api are exported - test('exported', () { - for (var value in [ - OpenDatabaseOptions, - DatabaseFactory, - Database, - Transaction, - Batch, - ConflictAlgorithm, - inMemoryDatabasePath, - OnDatabaseConfigureFn, - OnDatabaseCreateFn, - OnDatabaseOpenFn, - OnDatabaseVersionChangeFn, - onDatabaseDowngradeDelete, - sqfliteLogLevelNone, - sqfliteLogLevelSql, - sqfliteLogLevelVerbose, - ]) { - expect(value, isNotNull); - } - }); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/src_mixin_factory_test.dart b/sqflite/tripartite/sqflite_common/test/src_mixin_factory_test.dart deleted file mode 100644 index 28bb995c6ef3783be0da6ed4c726b16232e66780..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/src_mixin_factory_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/constant.dart'; -import 'package:sqflite_common/src/factory_mixin.dart'; -import 'package:sqflite_common/src/mixin/factory.dart'; -import 'package:test/test.dart'; - -import 'src_mixin_test.dart'; - -void main() { - group('mixin_factory', () { - test('public', () { - // ignore: unnecessary_statements - buildDatabaseFactory; - // ignore: unnecessary_statements - SqfliteInvokeHandler; - }); - test('buildDatabaseFactory', () async { - final methods = []; - final factory = buildDatabaseFactory( - tag: 'mock', - invokeMethod: (String method, [Object? arguments]) async { - final dynamic result = mockResult(method, arguments); - methods.add(method); - return result; - }); - expect((factory as SqfliteDatabaseFactoryMixin).tag, 'mock'); - // ignore: unnecessary_type_check - expect(factory is SqfliteInvokeHandler, isTrue); - await factory.openDatabase(inMemoryDatabasePath); - expect(methods, ['openDatabase']); - }); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/src_mixin_test.dart b/sqflite/tripartite/sqflite_common/test/src_mixin_test.dart deleted file mode 100644 index 6b03542623be1b6e675e3ac00bdc54bb13000ef4..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/src_mixin_test.dart +++ /dev/null @@ -1,820 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'dart:async'; - -import 'package:path/path.dart'; -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/constant.dart'; -import 'package:sqflite_common/src/database.dart'; -import 'package:sqflite_common/src/mixin.dart'; -import 'package:sqflite_common/src/mixin/dev_utils.dart'; // ignore: unused_import -import 'package:sqflite_common/src/open_options.dart'; -import 'package:sqflite_common/utils/utils.dart'; -import 'package:test/test.dart'; - -void main() { - group('src_mixin', () { - run(); - }); -} - -var _mockDatabasesPath = '.'; - -/// Mock the result based on the method used -Object? mockResult(String method, Object? arguments) { - Object? handleSqlMethod(String sqlMethod) { - switch (sqlMethod) { - case methodOpenDatabase: - return 1; - case methodInsert: - return 0; - case methodUpdate: - return 0; - case methodExecute: - return null; - case methodQuery: - return {}; - } - throw UnimplementedError('$method $sqlMethod $arguments'); - } - - // devPrint('$method'); - switch (method) { - case methodGetDatabasesPath: - return _mockDatabasesPath; - case methodOpenDatabase: - return 1; - case methodCloseDatabase: - return null; - case methodDeleteDatabase: - return null; - case methodDatabaseExists: - return true; - case methodInsert: - case methodUpdate: - case methodExecute: - case methodQuery: - return handleSqlMethod(method); - case methodBatch: - var operations = (arguments as Map)[paramOperations] as List; - var results = []; - for (var operation in operations) { - var sqlMethod = (operation as Map)[paramMethod] as String; - results.add(handleSqlMethod(sqlMethod)); - } - return results; - } - throw UnimplementedError('$method $arguments'); -} - -class MockDatabase extends SqfliteDatabaseBase { - MockDatabase(SqfliteDatabaseOpenHelper openHelper, [String name = 'mock']) - : super(openHelper, name); - - int? version; - List methods = []; - List sqls = []; - List?> argumentsLists = ?>[]; - - @override - Future invokeMethod(String method, [Object? arguments]) async { - // return super.invokeMethod(method, arguments); - - methods.add(method); - if (arguments is Map) { - argumentsLists.add(arguments.cast()); - if (arguments[paramOperations] != null) { - final operations = - arguments[paramOperations] as List>; - for (var operation in operations) { - final sql = operation[paramSql] as String?; - sqls.add(sql); - } - } else { - final sql = arguments[paramSql] as String?; - sqls.add(sql); - - // Basic version handling - if (sql?.startsWith('PRAGMA user_version = ') == true) { - version = int.tryParse(sql!.split(' ').last); - } else if (sql == 'PRAGMA user_version') { - return >[ - {'user_version': version} - ] as T; - } - } - } else { - argumentsLists.add(null); - sqls.add(null); - } - return mockResult(method, arguments) as T; - } -} - -class MockDatabaseFactory extends SqfliteDatabaseFactoryBase { - final List methods = []; - final List argumentsList = []; - final Map databases = {}; - - @override - Future invokeMethod(String method, [Object? arguments]) async { - methods.add(method); - argumentsList.add(arguments); - return mockResult(method, arguments) as T; - } - - SqfliteDatabase newEmptyDatabase() { - final path = 'empty'; - final helper = SqfliteDatabaseOpenHelper(this, path, OpenDatabaseOptions()); - final db = helper.newDatabase(path)..id = 1; - return db; - } - - @override - SqfliteDatabaseMixin newDatabase( - SqfliteDatabaseOpenHelper openHelper, String path) { - final existing = databases[path]; - final db = MockDatabase(openHelper, path); - // Copy version - db.version = existing?.version; - // Last replaces - databases[path] = db; - - return db; - } - - @override - Future getDatabasesPath() async { - return join('.dart_tool', 'sqlite', 'test', 'mock'); - } -} - -class MockDatabaseFactoryEmpty extends SqfliteDatabaseFactoryBase { - final List methods = []; - - @override - Future invokeMethod(String method, [Object? arguments]) async { - methods.add(method); - return mockResult(method, arguments) as T; - } -} - -final MockDatabaseFactory mockDatabaseFactory = MockDatabaseFactory(); - -void run() { - group('database_factory', () { - test('getDatabasesPath', () async { - final factory = MockDatabaseFactoryEmpty(); - await factory.getDatabasesPath(); - expect(factory.methods, ['getDatabasesPath']); - }); - test('setDatabasesPath', () async { - final factory = MockDatabaseFactoryEmpty(); - - factory.setDatabasesPathOrNull('.'); - expect(await factory.getDatabasesPath(), '.'); - - // reset - factory.setDatabasesPathOrNull(null); - expect(factory.methods, []); - - await factory.getDatabasesPath(); - expect(factory.methods, ['getDatabasesPath']); - //expect(directory, ) - }); - }); - group('database', () { - test('transaction', () async { - final Database db = mockDatabaseFactory.newEmptyDatabase(); - await db.execute('test'); - await db.insert('test', {'test': 1}); - await db.update('test', {'test': 1}); - await db.delete('test'); - await db.query('test'); - - await db.transaction((Transaction txn) async { - await txn.execute('test'); - await txn.insert('test', {'test': 1}); - await txn.update('test', {'test': 1}); - await txn.delete('test'); - await txn.query('test'); - }); - - final batch = db.batch(); - batch.execute('test'); - batch.insert('test', {'test': 1}); - batch.update('test', {'test': 1}); - batch.delete('test'); - batch.query('test'); - await batch.commit(); - }); - - group('open', () { - test('read-only', () async { - // var db = mockDatabaseFactory.newEmptyDatabase(); - final db = await mockDatabaseFactory.openDatabase('test', - options: SqfliteOpenDatabaseOptions(readOnly: true)) - as MockDatabase; - await db.close(); - expect(db.methods, ['openDatabase', 'closeDatabase']); - expect(db.argumentsLists.first, { - 'path': absolute( - join(await mockDatabaseFactory.getDatabasesPath(), 'test')), - 'readOnly': true, - 'singleInstance': true - }); - }); - test('not single_instance', () async { - // var db = mockDatabaseFactory.newEmptyDatabase(); - final db = await mockDatabaseFactory.openDatabase('single_instance.db', - options: SqfliteOpenDatabaseOptions(singleInstance: false)) - as MockDatabase; - await db.close(); - expect(db.methods, ['openDatabase', 'closeDatabase']); - expect(db.argumentsLists.first, { - 'path': absolute(join(await mockDatabaseFactory.getDatabasesPath(), - 'single_instance.db')), - 'singleInstance': false - }); - }); - - test('rollback transaction', () async { - // var db = mockDatabaseFactory.newEmptyDatabase(); - final db = await mockDatabaseFactory.openDatabase( - 'rollback_transaction.db', - options: SqfliteOpenDatabaseOptions(singleInstance: false)) - as MockDatabase; - await db.execute('BEGIN TRANSACTION'); - await db.close(); - expect(db.methods, - ['openDatabase', 'execute', 'execute', 'closeDatabase']); - expect(db.argumentsLists.first, { - 'path': absolute(join(await mockDatabaseFactory.getDatabasesPath(), - 'rollback_transaction.db')), - 'singleInstance': false - }); - expect(db.argumentsLists[2], { - 'sql': 'ROLLBACK', - 'id': 1, - 'transactionId': -1, - 'inTransaction': false - }); - }); - test('isOpen', () async { - // var db = mockDatabaseFactory.newEmptyDatabase(); - final db = await mockDatabaseFactory.openDatabase('is_open.db', - options: SqfliteOpenDatabaseOptions(readOnly: true)) - as MockDatabase; - expect(db.isOpen, true); - final closeFuture = db.close(); - // it is not closed right away - expect(db.isOpen, true); - await closeFuture; - expect(db.isOpen, false); - }); - - test('reOpenSameVersion', () async { - var db = await mockDatabaseFactory.openDatabase('on_reopen.db', - options: OpenDatabaseOptions( - version: 1, - )) as MockDatabase; - await db.close(); - - expect(db.sqls, [ - null, - 'PRAGMA user_version', - 'BEGIN EXCLUSIVE', - 'PRAGMA user_version', - 'PRAGMA user_version = 1', - 'COMMIT', - null - ]); - - db = await mockDatabaseFactory.openDatabase('on_reopen.db', - options: OpenDatabaseOptions( - version: 1, - )) as MockDatabase; - await db.close(); - - // Re-opening, no transaction is created - expect(db.sqls, [null, 'PRAGMA user_version', null]); - }); - }); - group('openTransaction', () { - test('onCreate', () async { - final db = await mockDatabaseFactory.openDatabase('on_create.db', - options: SqfliteOpenDatabaseOptions( - version: 1, - onCreate: (Database db, int version) async { - await db.execute('test1'); - await db.transaction((Transaction txn) async { - await txn.execute('test2'); - }); - })) as MockDatabase; - - await db.close(); - expect(db.methods, [ - 'openDatabase', - 'query', - 'execute', - 'query', - 'execute', - 'execute', - 'execute', - 'execute', - 'closeDatabase' - ]); - expect(db.sqls, [ - null, - 'PRAGMA user_version', - 'BEGIN EXCLUSIVE', - 'PRAGMA user_version', - 'test1', - 'test2', - 'PRAGMA user_version = 1', - 'COMMIT', - null - ]); - }); - - test('onConfigure', () async { - final db = await mockDatabaseFactory.openDatabase('on_configure.db', - options: OpenDatabaseOptions( - version: 1, - onConfigure: (Database db) async { - await db.execute('test1'); - await db.transaction((Transaction txn) async { - await txn.execute('test2'); - }); - })) as MockDatabase; - - await db.close(); - expect(db.sqls, [ - null, - 'test1', - 'BEGIN IMMEDIATE', - 'test2', - 'COMMIT', - 'PRAGMA user_version', - 'BEGIN EXCLUSIVE', - 'PRAGMA user_version', - 'PRAGMA user_version = 1', - 'COMMIT', - null - ]); - }); - - test('onOpen', () async { - final db = await mockDatabaseFactory.openDatabase('on_open', - options: OpenDatabaseOptions( - version: 1, - onOpen: (Database db) async { - await db.execute('test1'); - await db.transaction((Transaction txn) async { - await txn.execute('test2'); - }); - })) as MockDatabase; - - await db.close(); - expect(db.sqls, [ - null, - 'PRAGMA user_version', - 'BEGIN EXCLUSIVE', - 'PRAGMA user_version', - 'PRAGMA user_version = 1', - 'COMMIT', - 'test1', - 'BEGIN IMMEDIATE', - 'test2', - 'COMMIT', - null - ]); - }); - - test('batch', () async { - final db = await mockDatabaseFactory.openDatabase('test', - options: OpenDatabaseOptions( - version: 1, - onConfigure: (Database db) async { - final batch = db.batch(); - batch.execute('test1'); - await batch.commit(); - }, - onCreate: (db, _) async { - final batch = db.batch(); - batch.execute('test2'); - await batch.commit(noResult: true); - }, - onOpen: (Database db) async { - final batch = db.batch(); - batch.execute('test3'); - await batch.commit(continueOnError: true); - })) as MockDatabase; - - await db.close(); - expect(db.sqls, [ - null, - 'BEGIN IMMEDIATE', - 'test1', - 'COMMIT', - 'PRAGMA user_version', - 'BEGIN EXCLUSIVE', - 'PRAGMA user_version', - 'test2', - 'PRAGMA user_version = 1', - 'COMMIT', - 'BEGIN IMMEDIATE', - 'test3', - 'COMMIT', - null - ]); - expect(db.argumentsLists, [ - { - 'path': absolute( - join(await mockDatabaseFactory.getDatabasesPath(), 'test')), - 'singleInstance': true - }, - { - 'sql': 'BEGIN IMMEDIATE', - 'id': 1, - 'inTransaction': true, - 'transactionId': null - }, - { - 'operations': [ - { - 'method': 'execute', - 'sql': 'test1', - } - ], - 'id': 1 - }, - {'sql': 'COMMIT', 'id': 1, 'inTransaction': false}, - {'sql': 'PRAGMA user_version', 'id': 1}, - { - 'sql': 'BEGIN EXCLUSIVE', - 'inTransaction': true, - 'id': 1, - 'transactionId': null - }, - {'sql': 'PRAGMA user_version', 'id': 1}, - { - 'operations': >[ - { - 'method': 'execute', - 'sql': 'test2', - } - ], - 'id': 1, - 'noResult': true - }, - {'sql': 'PRAGMA user_version = 1', 'id': 1}, - {'sql': 'COMMIT', 'id': 1, 'inTransaction': false}, - { - 'sql': 'BEGIN IMMEDIATE', - 'id': 1, - 'inTransaction': true, - 'transactionId': null, - }, - { - 'operations': >[ - { - 'method': 'execute', - 'sql': 'test3', - } - ], - 'id': 1, - 'continueOnError': true - }, - {'sql': 'COMMIT', 'id': 1, 'inTransaction': false}, - {'id': 1} - ]); - }); - }); - - group('concurrency', () { - test('concurrent 1', () async { - final db = mockDatabaseFactory.newEmptyDatabase() as MockDatabase; - final step1 = Completer(); - final step2 = Completer(); - final step3 = Completer(); - - Future action1() async { - await db.execute('test'); - step1.complete(); - - await step2.future; - try { - await db.execute('test').timeout(const Duration(milliseconds: 100)); - throw 'should fail'; - } catch (e) { - expect(e is TimeoutException, true); - } - - step3.complete(); - } - - Future action2() async { - // This is the change with concurrency 2 - await step1.future; - await db.transaction((Transaction txn) async { - // Wait for table being created; - await txn.execute('test'); - step2.complete(); - - await step3.future; - - await txn.execute('test'); - }); - } - - final Future future1 = action1(); - final Future future2 = action2(); - - await Future.wait(>[future1, future2]); - // check ready - await db.transaction(((_) async {})); - }); - - test('concurrent 2', () async { - final db = mockDatabaseFactory.newEmptyDatabase() as MockDatabase; - final step1 = Completer(); - final step2 = Completer(); - final step3 = Completer(); - - Future action1() async { - await db.execute('test'); - step1.complete(); - - await step2.future; - try { - await db.execute('test').timeout(const Duration(milliseconds: 100)); - throw 'should fail'; - } catch (e) { - expect(e is TimeoutException, true); - } - - step3.complete(); - } - - Future action2() async { - await db.transaction((Transaction txn) async { - await step1.future; - // Wait for table being created; - await txn.execute('test'); - step2.complete(); - - await step3.future; - - await txn.execute('test'); - }); - } - - final Future future1 = action1(); - final Future future2 = action2(); - - await Future.wait(>[future1, future2]); - }); - }); - - group('compatibility 1', () { - test('concurrent 1', () async { - final db = mockDatabaseFactory.newEmptyDatabase() as MockDatabase; - final step1 = Completer(); - final step2 = Completer(); - final step3 = Completer(); - - Future action1() async { - await db.execute('test'); - step1.complete(); - - await step2.future; - try { - await db.execute('test').timeout(const Duration(milliseconds: 100)); - throw 'should fail'; - } catch (e) { - expect(e is TimeoutException, true); - } - - step3.complete(); - } - - Future action2() async { - // This is the change with concurrency 2 - await step1.future; - await db.transaction((Transaction txn) async { - // Wait for table being created; - await txn.execute('test'); - step2.complete(); - - await step3.future; - - await txn.execute('test'); - }); - } - - final Future future1 = action1(); - final Future future2 = action2(); - - await Future.wait(>[future1, future2]); - // check ready - await db.transaction(((_) async {})); - }); - - test('concurrent 2', () async { - final db = mockDatabaseFactory.newEmptyDatabase() as MockDatabase; - final step1 = Completer(); - final step2 = Completer(); - final step3 = Completer(); - - Future action1() async { - await step1.future; - try { - await db.execute('test').timeout(const Duration(milliseconds: 100)); - throw 'should fail'; - } catch (e) { - expect(e is TimeoutException, true); - } - - await step2.future; - try { - await db.execute('test').timeout(const Duration(milliseconds: 100)); - throw 'should fail'; - } catch (e) { - expect(e is TimeoutException, true); - } - - step3.complete(); - } - - Future action2() async { - await db.transaction((Transaction txn) async { - step1.complete(); - - // Wait for table being created; - await txn.execute('test'); - step2.complete(); - - await step3.future; - - await txn.execute('test'); - }); - } - - final Future future2 = action2(); - final Future future1 = action1(); - - await Future.wait(>[future1, future2]); - // check ready - await db.transaction(((_) async {})); - }); - }); - - group('batch', () { - test('simple', () async { - final db = await mockDatabaseFactory.openDatabase('batch_simple.db') - as MockDatabase; - - final batch = db.batch(); - batch.execute('test'); - await batch.commit(); - await batch.commit(); - await db.close(); - expect(db.methods, [ - 'openDatabase', - 'execute', - 'batch', - 'execute', - 'execute', - 'batch', - 'execute', - 'closeDatabase' - ]); - expect(db.sqls, [ - null, - 'BEGIN IMMEDIATE', - 'test', - 'COMMIT', - 'BEGIN IMMEDIATE', - 'test', - 'COMMIT', - null - ]); - }); - - test('in_transaction', () async { - final db = await mockDatabaseFactory - .openDatabase('batch_in_transaction.db') as MockDatabase; - - await db.transaction((Transaction txn) async { - final batch = txn.batch(); - batch.execute('test'); - - await batch.commit(); - await batch.commit(); - }); - await db.close(); - expect(db.methods, [ - 'openDatabase', - 'execute', - 'batch', - 'batch', - 'execute', - 'closeDatabase' - ]); - expect(db.sqls, - [null, 'BEGIN IMMEDIATE', 'test', 'test', 'COMMIT', null]); - }); - }); - - group('instances', () { - test('singleInstance same', () async { - final futureDb1 = mockDatabaseFactory.openDatabase('test', - options: OpenDatabaseOptions(singleInstance: true)); - final db2 = await mockDatabaseFactory.openDatabase('test', - options: OpenDatabaseOptions(singleInstance: true)) as MockDatabase; - final db1 = await futureDb1 as MockDatabase; - expect(db1, db2); - }); - test('singleInstance', () async { - final futureDb1 = mockDatabaseFactory.openDatabase('test', - options: OpenDatabaseOptions(singleInstance: true)); - final db2 = await mockDatabaseFactory.openDatabase('test', - options: OpenDatabaseOptions(singleInstance: true)) as MockDatabase; - final db1 = await futureDb1 as MockDatabase; - final db3 = await mockDatabaseFactory.openDatabase('other', - options: OpenDatabaseOptions(singleInstance: true)) as MockDatabase; - final db4 = await mockDatabaseFactory.openDatabase(join('.', 'other'), - options: OpenDatabaseOptions(singleInstance: true)) as MockDatabase; - //expect(db1, db2); - expect(db1, isNot(db3)); - expect(db3, db4); - await db1.close(); - await db2.close(); - await db3.close(); - }); - - test('multiInstances', () async { - final futureDb1 = mockDatabaseFactory.openDatabase('multi_instances.db', - options: OpenDatabaseOptions(singleInstance: false)); - final db2 = await mockDatabaseFactory.openDatabase('multi_instances.db', - options: OpenDatabaseOptions(singleInstance: false)) - as MockDatabase; - final db1 = await futureDb1 as MockDatabase; - expect(db1, isNot(db2)); - await db1.close(); - await db2.close(); - }); - }); - - test('dead lock', () async { - final db = mockDatabaseFactory.newEmptyDatabase() as MockDatabase; - var hasTimedOut = false; - var callbackCount = 0; - setLockWarningInfo( - duration: const Duration(milliseconds: 200), - callback: () { - callbackCount++; - }); - try { - await db.transaction((Transaction txn) async { - await db.execute('test'); - fail('should fail'); - }).timeout(const Duration(milliseconds: 500)); - } on TimeoutException catch (_) { - hasTimedOut = true; - } - expect(hasTimedOut, isTrue); - expect(callbackCount, 1); - await db.close(); - }); - - test('deleted/exists', () async { - final path = 'test_exists.db'; - await mockDatabaseFactory.deleteDatabase(path); - final exists = await mockDatabaseFactory.databaseExists(path); - expect(exists, isTrue); - final expectedPath = - absolute(join(await mockDatabaseFactory.getDatabasesPath(), path)); - expect(mockDatabaseFactory.methods, - ['deleteDatabase', 'databaseExists']); - expect(mockDatabaseFactory.argumentsList, >[ - {'path': expectedPath}, - {'path': expectedPath} - ]); - }); - }); -} diff --git a/sqflite/tripartite/sqflite_common/test/test_scenario.dart b/sqflite/tripartite/sqflite_common/test/test_scenario.dart deleted file mode 100644 index 764d621778ce6fe776cda064d7b814d49ea60518..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/test_scenario.dart +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common/src/mixin/import_mixin.dart'; -import 'package:test/test.dart'; - -/// Common open step -var protocolOpenStep = [ - 'openDatabase', - {'path': ':memory:', 'singleInstance': false}, - {'id': 1} -]; - -/// Common close step -var protocolCloseStep = [ - 'closeDatabase', - {'id': 1}, - null -]; - -class MockMethodCall { - String? expectedMethod; - dynamic expectedArguments; - - /// Response can be an exception - dynamic response; - - @override - String toString() => '$expectedMethod $expectedArguments $response'; -} - -class MockScenario { - MockScenario(this.factory, List data) { - methodsCalls = data - .map((list) => MockMethodCall() - ..expectedMethod = list[0]?.toString() - ..expectedArguments = list[1] - ..response = list[2]) - .toList(growable: false); - } - - final DatabaseFactory factory; - late List methodsCalls; - var index = 0; - dynamic exception; - - void end() { - expect(exception, isNull, reason: '$exception'); - expect(index, methodsCalls.length); - } -} - -MockScenario startScenario(List data) { - late MockScenario scenario; - final databaseFactoryMock = buildDatabaseFactory( - tag: 'mock', - invokeMethod: (String method, [Object? arguments]) async { - final index = scenario.index++; - // devPrint('$index ${scenario.methodsCalls[index]}'); - final item = scenario.methodsCalls[index]; - try { - expect(method, item.expectedMethod); - expect(arguments, item.expectedArguments); - } catch (e) { - // devPrint(e); - scenario.exception ??= '$e $index'; - } - if (item.response is DatabaseException) { - throw item.response as DatabaseException; - } - return item.response; - }); - scenario = MockScenario(databaseFactoryMock, data); - return scenario; -} diff --git a/sqflite/tripartite/sqflite_common/test/utils_test.dart b/sqflite/tripartite/sqflite_common/test/utils_test.dart deleted file mode 100644 index ce46628c1f4a1a9986da3e39ac3012983b89f06e..0000000000000000000000000000000000000000 --- a/sqflite/tripartite/sqflite_common/test/utils_test.dart +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:sqflite_common/src/utils.dart'; -import 'package:sqflite_common/utils/utils.dart'; -import 'package:test/test.dart'; - -void main() { - group('sqflite', () { - test('firstIntValue', () { - expect( - firstIntValue(>[ - {'test': 1} - ]), - 1); - expect( - firstIntValue(>[ - {'test': 1}, - {'test': 1} - ]), - 1); - expect( - firstIntValue(>[ - {'test': null} - ]), - null); - expect( - firstIntValue(>[{}]), isNull); - expect(firstIntValue(>[]), isNull); - expect( - firstIntValue(>[{}]), isNull); - }); - - test('hex', () { - expect( - hex([ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 16, - 17, - 255 - ]), - '000102030405060708090A0B0C0D0E0F1011FF'); - expect(hex([]), ''); - expect(hex([32]), '20'); - - try { - hex([-1]); - fail('should fail'); - } on FormatException catch (_) {} - - try { - hex([256]); - fail('should fail'); - } on FormatException catch (_) {} - }); - - test('chunk', () { - expect(listChunk([], null), isEmpty); - expect(listChunk([1], null), [ - [1] - ]); - expect(listChunk([1], 0), [ - [1] - ]); - expect(listChunk([1, 2], 0), [ - [1, 2] - ]); - expect(listChunk([1, 2], 2), [ - [1, 2] - ]); - expect(listChunk([1, 2], 3), [ - [1, 2] - ]); - expect(listChunk([1, 2], 1), [ - [1], - [2] - ]); - expect(listChunk([1, 2, 3], 2), [ - [1, 2], - [3] - ]); - }); - }); -} diff --git a/sqflite_common/.gitignore b/sqflite_common/.gitignore deleted file mode 100644 index 1d294b89b479456145a09a4ccba5814d5a235f28..0000000000000000000000000000000000000000 --- a/sqflite_common/.gitignore +++ /dev/null @@ -1,19 +0,0 @@ -.DS_Store -.packages -.pub/ -ios/.generated/ -packages -pubspec.lock - -# Directory created by dartdoc -doc/api/ - -# Local folder -.local/ - -# Conventional directory for build outputs -build/ -coverage/ - -# flutter -.metadata \ No newline at end of file diff --git a/sqflite_common/CHANGELOG.md b/sqflite_common/CHANGELOG.md index 20651cdf077a1c0aa4a93e3b686231a88e1bf333..a3cf92c318a2dd02a8764aedffeaf483baf64366 100644 --- a/sqflite_common/CHANGELOG.md +++ b/sqflite_common/CHANGELOG.md @@ -1,8 +1,3 @@ -## 2.5.0 - -* Dart 3 only -* Add `readDatabaseBytes` and `writeDatabaseBytes` factory methods. - ## 2.4.5+1 * Add global API from sqflite (openDatabase, deleteDatabase, databaseFactory...) from sqflite diff --git a/sqflite_common/analysis_options.yaml b/sqflite_common/analysis_options.yaml index cbbe118c67992fb19c23188e207b391f950c3075..25cf80a97c983719acc56a070ea2bc091e2c7890 100644 --- a/sqflite_common/analysis_options.yaml +++ b/sqflite_common/analysis_options.yaml @@ -45,8 +45,9 @@ linter: - directives_ordering - empty_catches - hash_and_equals - - collection_methods_unrelated_type + - iterable_contains_unrelated_type - library_private_types_in_public_api + - list_remove_unrelated_type - no_adjacent_strings_in_list - no_duplicate_case_values - no_leading_underscores_for_library_prefixes diff --git a/sqflite_common/lib/sqlite_api.dart b/sqflite_common/lib/sqlite_api.dart index 2ad59e12ffb78fd038fb4318e7478e24e6dfbe5b..91e82d0aa8d528477a840373233040a158d90be8 100644 --- a/sqflite_common/lib/sqlite_api.dart +++ b/sqflite_common/lib/sqlite_api.dart @@ -1,5 +1,4 @@ import 'dart:async'; -import 'dart:typed_data'; import 'package:sqflite_common/sql.dart' show ConflictAlgorithm; import 'package:sqflite_common/src/database.dart'; @@ -54,12 +53,6 @@ abstract class DatabaseFactory { /// Check if a database exists Future databaseExists(String path); - - /// Write database bytes. - Future writeDatabaseBytes(String path, Uint8List bytes); - - /// Read database bytes. - Future readDatabaseBytes(String path); } /// diff --git a/sqflite_common/lib/src/constant.dart b/sqflite_common/lib/src/constant.dart index 10fad65d35ab9fb86e07d79e60b184ed7527a246..209dd42006a8aa95991fdc5dfccc2aab652daf68 100644 --- a/sqflite_common/lib/src/constant.dart +++ b/sqflite_common/lib/src/constant.dart @@ -44,12 +44,6 @@ const String methodDatabaseExists = 'databaseExists'; /// Native database delete method. const String methodDeleteDatabase = 'deleteDatabase'; -/// Native write database bytes method. -const String methodWriteDatabaseBytes = 'writeDatabaseBytes'; - -/// Native read database bytes method. -const String methodReadDatabaseBytes = 'readDatabaseBytes'; - /// Native batch operations parameter. const String paramOperations = 'operations'; @@ -98,9 +92,6 @@ const String paramRecoveredInTransaction = 'recoveredInTransaction'; /// The database path (string). const String paramPath = 'path'; -/// Bytes content. -const String paramBytes = 'bytes'; - /// The database version (int). const String paramVersion = 'version'; diff --git a/sqflite_common/lib/src/database_file_system.dart b/sqflite_common/lib/src/database_file_system.dart deleted file mode 100644 index d64466630abdd65153d70e5bb82ca28ecdcd0b34..0000000000000000000000000000000000000000 --- a/sqflite_common/lib/src/database_file_system.dart +++ /dev/null @@ -1,16 +0,0 @@ -import 'dart:typed_data'; - -/// Abstract lightweight database file system. -abstract class DatabaseFileSystem { - /// Delete the database file including its journal file and other auxiliary files - Future deleteDatabase(String path); - - /// Read a database file as bytes. - Future readDatabaseBytes(String path); - - /// Write database files bytes. - Future writeDatabaseBytes(String path, Uint8List bytes); - - /// Check if database file exists. - Future databaseExists(String path); -} diff --git a/sqflite_common/lib/src/database_file_system_io.dart b/sqflite_common/lib/src/database_file_system_io.dart deleted file mode 100644 index 9cc4c389f0db177a226f0d0fee41d9c1b8633f40..0000000000000000000000000000000000000000 --- a/sqflite_common/lib/src/database_file_system_io.dart +++ /dev/null @@ -1,51 +0,0 @@ -import 'dart:io'; -import 'dart:typed_data'; - -import 'database_file_system.dart'; - -/// IO implementation of [DatabaseFileSystem] -class DatabaseFileSystemIo implements DatabaseFileSystem { - /// Safe delete a files - Future _safeDeleteFile(String path) async { - try { - await File(path).delete(recursive: true); - } catch (_) {} - } - - /// Delete the database file including its journal file and other auxiliary files - @override - Future deleteDatabase(String path) async { - await _safeDeleteFile(path); - await _safeDeleteFile('$path-wal'); - await _safeDeleteFile('$path-shm'); - await _safeDeleteFile('$path-journal'); - } - - /// Read a database file as bytes. - @override - Future readDatabaseBytes(String path) async { - return await File(path).readAsBytes(); - } - - /// Write database files bytes. - @override - Future writeDatabaseBytes(String path, Uint8List bytes) async { - var file = File(path); - var dir = file.parent; - if (!dir.existsSync()) { - await dir.create(recursive: true); - } - await file.writeAsBytes(bytes, flush: true); - } - - /// Check if database file exists. - @override - Future databaseExists(String path) async { - // Ignore failure - try { - return (File(path)).existsSync(); - } catch (_) { - return false; - } - } -} diff --git a/sqflite_common/lib/src/factory.dart b/sqflite_common/lib/src/factory.dart index 42450a0bee6e72d2f538f5090c31564f9b662477..60d3247a10b8400c67b0af8a82e7c67081366bcd 100644 --- a/sqflite_common/lib/src/factory.dart +++ b/sqflite_common/lib/src/factory.dart @@ -27,11 +27,9 @@ abstract class SqfliteDatabaseFactory /// db.close() calls this right await. Future closeDatabase(SqfliteDatabase database); - /// Delete the database file. @override Future deleteDatabase(String path); - /// Check if a database exists. @override Future databaseExists(String path); } diff --git a/sqflite_common/lib/src/factory_mixin.dart b/sqflite_common/lib/src/factory_mixin.dart index 94b86d70ba4d1f25ad47ec4f34f72366b5f13c15..9d948d01ec59ecf9de309435284536d4a3da7353 100644 --- a/sqflite_common/lib/src/factory_mixin.dart +++ b/sqflite_common/lib/src/factory_mixin.dart @@ -1,5 +1,3 @@ -import 'dart:typed_data'; - import 'package:path/path.dart'; import 'package:sqflite_common/sqlite_api.dart'; import 'package:sqflite_common/src/constant.dart'; @@ -145,30 +143,6 @@ mixin SqfliteDatabaseFactoryMixin methodDatabaseExists, {paramPath: path}); } - @override - Future writeDatabaseBytes(String path, Uint8List bytes) async { - path = await fixPath(path); - final lock = _getDatabaseOpenLock(path); - return lock.synchronized(() async { - return safeInvokeMethod(methodWriteDatabaseBytes, - {paramPath: path, paramBytes: bytes}); - }); - } - - @override - Future readDatabaseBytes(String path) async { - path = await fixPath(path); - final lock = _getDatabaseOpenLock(path); - return lock.synchronized(() async { - var result = await safeInvokeMethod( - methodReadDatabaseBytes, {paramPath: path}); - if (result is Map) { - return result[paramBytes] as Uint8List; - } - throw ArgumentError('Invalid result $result'); - }); - } - String? _databasesPath; @override diff --git a/sqflite_common/lib/src/mixin/platform.dart b/sqflite_common/lib/src/mixin/platform.dart deleted file mode 100644 index ca85ee0ab49a090c8f40cf46b764e6737c345031..0000000000000000000000000000000000000000 --- a/sqflite_common/lib/src/mixin/platform.dart +++ /dev/null @@ -1,4 +0,0 @@ -export 'package:sqflite_common/src/database_file_system.dart' - show DatabaseFileSystem; -export 'package:sqflite_common/src/platform/platform.dart' - show Platform, platform; diff --git a/sqflite_common/lib/src/platform/platform.dart b/sqflite_common/lib/src/platform/platform.dart index f11c0886897897ca8562fe972fc0d79c8476e585..42c7d429913823bf2392b509eca364e959cad58a 100644 --- a/sqflite_common/lib/src/platform/platform.dart +++ b/sqflite_common/lib/src/platform/platform.dart @@ -1,5 +1,3 @@ -import 'package:sqflite_common/src/database_file_system.dart'; - export 'platform_io.dart' if (dart.library.js) 'platform_web.dart'; /// IO/web support @@ -21,7 +19,4 @@ abstract class Platform { /// True if IO MacOS bool get isMacOS => false; - - /// Database file system. - DatabaseFileSystem get databaseFileSystem; } diff --git a/sqflite_common/lib/src/platform/platform_io.dart b/sqflite_common/lib/src/platform/platform_io.dart index 2fd7fc04a5e27221b3f61a506d94d48ebd054188..fc68d2d89a3c6b1a82e118617fed0a6d4177e712 100644 --- a/sqflite_common/lib/src/platform/platform_io.dart +++ b/sqflite_common/lib/src/platform/platform_io.dart @@ -1,7 +1,5 @@ import 'dart:io' as io; -import 'package:sqflite_common/src/database_file_system.dart'; -import 'package:sqflite_common/src/database_file_system_io.dart'; import 'package:sqflite_common/src/platform/platform.dart'; class _PlatformIo extends Platform { @@ -19,9 +17,6 @@ class _PlatformIo extends Platform { @override bool get isMacOS => io.Platform.isMacOS; - - @override - DatabaseFileSystem get databaseFileSystem => DatabaseFileSystemIo(); } /// Platform (IO) diff --git a/sqflite_common/lib/src/platform/platform_web.dart b/sqflite_common/lib/src/platform/platform_web.dart index 17eee1942fcfec0b43ecfd29ff7a82c082d61802..80e287d72d9757db0515892c387b331839c142b6 100644 --- a/sqflite_common/lib/src/platform/platform_web.dart +++ b/sqflite_common/lib/src/platform/platform_web.dart @@ -1,13 +1,8 @@ -import 'package:sqflite_common/src/database_file_system.dart'; import 'package:sqflite_common/src/platform/platform.dart'; class _PlatformWeb extends Platform { @override bool get isWeb => false; - - @override - DatabaseFileSystem get databaseFileSystem => - throw UnimplementedError('$runtimeType.databaseFileSystem'); } /// Platform (Web) diff --git a/sqflite_common/pubspec.yaml b/sqflite_common/pubspec.yaml index 36e7d3666031962bf915f992af1becec8e41fc36..dbfe02a17949b4999941fb93410ea78bf0dc0568 100644 --- a/sqflite_common/pubspec.yaml +++ b/sqflite_common/pubspec.yaml @@ -1,12 +1,12 @@ name: sqflite_common homepage: https://github.com/tekartik/sqflite/tree/master/sqflite_common description: Dart wrapper on SQLite, a self-contained, high-reliability, embedded, SQL database engine. -version: 2.5.0 +version: 2.4.5+1 funding: - https://github.com/sponsors/alextekartik environment: - sdk: '>=3.0.0 <4.0.0' + sdk: '>=2.18.0 <4.0.0' dependencies: synchronized: '>=3.0.0 <5.0.0' @@ -19,4 +19,4 @@ dev_dependencies: http: '>=0.13.0' test: '>=1.16.2' test_api: '>=0.2.19' - pub_semver: '>=2.0.0' + pub_semver: '>=2.0.0' \ No newline at end of file diff --git a/sqflite_common/test/database_file_system_io_test.dart b/sqflite_common/test/database_file_system_io_test.dart deleted file mode 100644 index cc3e1eb725d0b08b12df6021ba1a5c8c53e1ef07..0000000000000000000000000000000000000000 --- a/sqflite_common/test/database_file_system_io_test.dart +++ /dev/null @@ -1,22 +0,0 @@ -import 'dart:typed_data'; -import 'package:path/path.dart'; -import 'package:sqflite_common/src/database_file_system_io.dart'; -import 'package:test/test.dart'; - -void main() { - var fileSystem = DatabaseFileSystemIo(); - group('database_file_sytem_io', () { - test('read/write', () async { - var path = join( - '.dart_tool', 'sqflite_common', 'database_file_sytem_io', 'test.db'); - await fileSystem.deleteDatabase(path); - try { - await fileSystem.readDatabaseBytes(path); - } catch (e) { - print(e); - } - await fileSystem.writeDatabaseBytes(path, Uint8List.fromList([1, 2, 3])); - expect(await fileSystem.readDatabaseBytes(path), [1, 2, 3]); - }); - }); -} diff --git a/sqflite_common/test/sqflite_open_test.dart b/sqflite_common/test/sqflite_open_test.dart index d65536902a960a8015c3d54014a3f9b4e8ae74cd..2933d8e1acf85a7b57dc7f0128ef7e052710a1bf 100644 --- a/sqflite_common/test/sqflite_open_test.dart +++ b/sqflite_common/test/sqflite_open_test.dart @@ -1,5 +1,3 @@ -import 'dart:typed_data'; - import 'package:sqflite_common/sqlite_api.dart'; import 'package:test/test.dart'; @@ -85,30 +83,5 @@ void main() { await db.close(); scenario.end(); }); - test('read/write', () async { - final scenario = startScenario([ - [ - 'writeDatabaseBytes', - { - 'path': ':memory:', - 'bytes': [1, 2, 3], - }, - null, - ], - [ - 'readDatabaseBytes', - {'path': ':memory:'}, - { - 'bytes': Uint8List.fromList([1, 2, 3]) - } - ], - ]); - final factory = scenario.factory; - await factory.writeDatabaseBytes( - inMemoryDatabasePath, Uint8List.fromList([1, 2, 3])); - expect(await factory.readDatabaseBytes(inMemoryDatabasePath), [1, 2, 3]); - - scenario.end(); - }); }); } diff --git a/sqflite_common_ffi/.gitignore b/sqflite_common_ffi/.gitignore deleted file mode 100644 index f92ff8f4387e001c1065af33d78836d66f76c9e8..0000000000000000000000000000000000000000 --- a/sqflite_common_ffi/.gitignore +++ /dev/null @@ -1,76 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -**/doc/api/ -.dart_tool/ -.flutter-plugins -.flutter-plugins-dependencies -.packages -.pub-cache/ -.pub/ -build/ - -# Android related -**/android/**/gradle-wrapper.jar -**/android/.gradle -**/android/captures/ -**/android/gradlew -**/android/gradlew.bat -**/android/local.properties -**/android/**/GeneratedPluginRegistrant.java - -# iOS/XCode related -**/ios/**/*.mode1v3 -**/ios/**/*.mode2v3 -**/ios/**/*.moved-aside -**/ios/**/*.pbxuser -**/ios/**/*.perspectivev3 -**/ios/**/*sync/ -**/ios/**/.sconsign.dblite -**/ios/**/.tags* -**/ios/**/.vagrant/ -**/ios/**/DerivedData/ -**/ios/**/Icon? -**/ios/**/Pods/ -**/ios/**/.symlinks/ -**/ios/**/profile -**/ios/**/xcuserdata -**/ios/.generated/ -**/ios/Flutter/App.framework -**/ios/Flutter/Flutter.framework -**/ios/Flutter/Flutter.podspec -**/ios/Flutter/Generated.xcconfig -**/ios/Flutter/app.flx -**/ios/Flutter/app.zip -**/ios/Flutter/flutter_assets/ -**/ios/Flutter/flutter_export_environment.sh -**/ios/ServiceDefinitions.json -**/ios/Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!**/ios/**/default.mode1v3 -!**/ios/**/default.mode2v3 -!**/ios/**/default.pbxuser -!**/ios/**/default.perspectivev3 -!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages -/.metadata diff --git a/sqflite_common_ffi/CHANGELOG.md b/sqflite_common_ffi/CHANGELOG.md index 14aca600a0de4a78e2b8e3e31bbd2e8f3ec4eef2..088b2316d9caacdc5ab4d03d6b5e318b1b296abd 100644 --- a/sqflite_common_ffi/CHANGELOG.md +++ b/sqflite_common_ffi/CHANGELOG.md @@ -1,8 +1,3 @@ -## 2.3.0+2 - -* Dart 3 only. -* Bundle Windows sqlite3.dll 3.42.0 - ## 2.2.5 * Export global sqflite API diff --git a/sqflite_common_ffi/README.md b/sqflite_common_ffi/README.md index b50592ab5da5aa901dd06cca8bd7081f400773c0..330976a977151ba255fa632f4b9c1a3ac0afe2f2 100644 --- a/sqflite_common_ffi/README.md +++ b/sqflite_common_ffi/README.md @@ -114,45 +114,6 @@ Future main() async { } ``` -Example with path_provider - -```dart -import 'dart:io' as io; -import 'package:path/path.dart' as p; -import 'package:sqflite_common/sqlite_api.dart'; -import 'package:sqflite_common_ffi/sqflite_ffi.dart'; -import 'package:path_provider/path_provider.dart'; - -Future main() async { - // Init ffi loader if needed. - sqfliteFfiInit(); - - var databaseFactory = databaseFactoryFfi; - final io.Directory appDocumentsDir = await getApplicationDocumentsDirectory(); - - //Create path for database - String dbPath = p.join(appDocumentsDir.path, "databases", "myDb.db"); - var db = await databaseFactory.openDatabase( - dbPath, - ); - - await db.execute(''' - CREATE TABLE Product ( - id INTEGER PRIMARY KEY, - title TEXT - ) - '''); - await db.insert('Product', {'title': 'Product 1'}); - await db.insert('Product', {'title': 'Product 1'}); - - var result = await db.query('Product'); - print(result); - // prints [{id: 1, title: Product 1}, {id: 2, title: Product 1}] - await db.close(); -} - -``` - If your existing application uses sqflite on iOS/Android/MacOS, you can also set the proper initialization to have your application [work on Linux and windows](https://github.com/tekartik/sqflite/blob/master/sqflite_common_ffi/doc/using_ffi_instead_of_sqflite.md). diff --git a/sqflite_common_ffi/analysis_options.yaml b/sqflite_common_ffi/analysis_options.yaml index 6e8f4c40cfa265178fe1a37fdcc5d77e6e7be9e6..b18b29f43539ab07805d1a6e70d5a657c14d05bb 100644 --- a/sqflite_common_ffi/analysis_options.yaml +++ b/sqflite_common_ffi/analysis_options.yaml @@ -45,7 +45,8 @@ linter: - directives_ordering - empty_catches - hash_and_equals - - collection_methods_unrelated_type + - iterable_contains_unrelated_type + - list_remove_unrelated_type - no_adjacent_strings_in_list - no_duplicate_case_values - non_constant_identifier_names diff --git a/sqflite_common_ffi/doc/updating_sqlite_dll.md b/sqflite_common_ffi/doc/updating_sqlite_dll.md deleted file mode 100644 index f53fbdeeddd737da824d722fb108c7fab60e2d63..0000000000000000000000000000000000000000 --- a/sqflite_common_ffi/doc/updating_sqlite_dll.md +++ /dev/null @@ -1,10 +0,0 @@ -# Updating SQLite DLL - -This projects ships with a precompiled version of the SQLite DLL for Windows that allows running dart and flutter app -without additional setup. This version might not be the latest available at https://www.sqlite.org/download.html. - -You should grab and copy a fresh version of sqlite3.dll for your released app to bundle with your app. - -## Upgrading SQLite dll - -`sqlite3_info.dart` can be modified to download a new version of the SQLite DLL by running `tool/windows_setup.dart`. diff --git a/sqflite_common_ffi/lib/src/sqflite_ffi_handler.dart b/sqflite_common_ffi/lib/src/sqflite_ffi_handler.dart deleted file mode 100644 index ee3a011c46bc41840d8ff02f7cec3c5fab5b4954..0000000000000000000000000000000000000000 --- a/sqflite_common_ffi/lib/src/sqflite_ffi_handler.dart +++ /dev/null @@ -1,40 +0,0 @@ -import 'dart:async'; -import 'dart:typed_data'; - -// ignore: implementation_imports -import 'package:sqlite3/common.dart' as common; - -/// Ffi handler. -abstract class SqfliteFfiHandler { - /// Opens the database using an ffi implementation - Future openPlatform(Map argumentsMap); - - /// Delete the database file. - Future deleteDatabasePlatform(String path); - - /// Write the database i/o bytes. - Future writeDatabaseBytesPlatform(String path, Uint8List bytes); - - /// Write the database i/o bytes. - Future readDatabaseBytesPlatform(String path); - - /// Check if database file exists - Future handleDatabaseExistsPlatform(String path); - - /// Default database path. - String getDatabasesPathPlatform(); - - /// Ffi specific options (for the web contains the sqlite3 wasm url) - Future handleOptionsPlatform(Map argumentMap); -} - -/// Base unimplemented mixin. -mixin SqfliteFfiHandlerNonImplementedMixin implements SqfliteFfiHandler { - @override - Future writeDatabaseBytesPlatform(String path, Uint8List bytes) => - throw UnimplementedError('$runtimeType.writeDatabaseBytesPlatform'); - - @override - Future readDatabaseBytesPlatform(String path) => - throw UnimplementedError('$runtimeType.readDatabaseBytesPlatform'); -} diff --git a/sqflite_common_ffi/lib/src/sqflite_ffi_impl.dart b/sqflite_common_ffi/lib/src/sqflite_ffi_impl.dart index 3ebd4f9ef76b45ab9577fe85cc8560cddc9bd980..c8858c5b85fae65a65bca8e8f7a16506559c847e 100644 --- a/sqflite_common_ffi/lib/src/sqflite_ffi_impl.dart +++ b/sqflite_common_ffi/lib/src/sqflite_ffi_impl.dart @@ -5,7 +5,6 @@ import 'package:path/path.dart'; import 'package:sqflite_common/src/mixin/constant.dart'; // ignore: implementation_imports import 'package:sqflite_common_ffi/src/constant.dart'; import 'package:sqflite_common_ffi/src/sqflite_ffi_exception.dart'; -import 'package:sqflite_common_ffi/src/sqflite_ffi_handler.dart'; import 'package:sqlite3/common.dart' as common; import 'package:synchronized/synchronized.dart'; @@ -14,13 +13,28 @@ import 'import.dart'; import 'sqflite_ffi_impl_io.dart' if (dart.library.js) 'sqflite_ffi_impl_web.dart'; -export 'sqflite_ffi_handler.dart' - show SqfliteFfiHandler; // compatibility, was defined here before - final _debug = false; // devWarning(true); // false final _globalHandlerLock = Lock(); +/// Ffi handler. +abstract class SqfliteFfiHandler { + /// Opens the database using an ffi implementation + Future openPlatform(Map argumentsMap); + + /// Delete the database file. + Future deleteDatabasePlatform(String path); + + /// Check if database file exists + Future handleDatabaseExistsPlatform(String path); + + /// Default database path. + String getDatabasesPathPlatform(); + + /// Ffi specific options (for the web contains the sqlite3 wasm url) + Future handleOptionsPlatform(Map argumentMap); +} + /// By id var ffiDbs = {}; @@ -680,10 +694,6 @@ extension SqfliteFfiMethodCallHandler on FfiMethodCall { return await _wrapGlobalHandler(handleDatabaseExists); case methodOptions: return await _wrapGlobalHandler(handleOptions); - case methodWriteDatabaseBytes: - return await _wrapGlobalHandler(handleWriteDatabaseBytes); - case methodReadDatabaseBytes: - return await _wrapGlobalHandler(handleReadDatabaseBytes); // compat case 'debugMode': return await handleDebugMode(); @@ -824,12 +834,6 @@ extension SqfliteFfiMethodCallHandler on FfiMethodCall { return path; } - /// Get the `bytes` argument as Uint8List. - Uint8List? getBytes() { - var bytes = _getParam(paramBytes); - return bytes; - } - /// Check the arguments List? getSqlArguments() { var sqlArguments = _getParam(paramSqlArguments); @@ -1020,20 +1024,6 @@ extension SqfliteFfiMethodCallHandler on FfiMethodCall { var path = getPath(); return sqfliteFfiHandler.handleDatabaseExistsPlatform(path!); } - - /// Handle `readDatabaseBytes`. - Future handleReadDatabaseBytes() async { - var path = getPath(); - var bytes = await sqfliteFfiHandler.readDatabaseBytesPlatform(path!); - return {paramBytes: bytes}; - } - - /// Handle `writeDatabaseBytes`. - Future handleWriteDatabaseBytes() async { - var path = getPath(); - var bytes = getBytes(); - return sqfliteFfiHandler.writeDatabaseBytesPlatform(path!, bytes!); - } } /// Pack the result in the expected sqflite format. diff --git a/sqflite_common_ffi/lib/src/sqflite_ffi_impl_io.dart b/sqflite_common_ffi/lib/src/sqflite_ffi_impl_io.dart index be427abe094aff9d4a68f37b24e82f4f6392f433..5622d26b9c525a92cea67cc7105940747fb61fb0 100644 --- a/sqflite_common_ffi/lib/src/sqflite_ffi_impl_io.dart +++ b/sqflite_common_ffi/lib/src/sqflite_ffi_impl_io.dart @@ -1,19 +1,17 @@ import 'dart:io'; -import 'dart:typed_data'; // import 'dart:typed_data'; import 'package:path/path.dart'; import 'package:sqflite_common/src/mixin/constant.dart'; // ignore: implementation_imports -import 'package:sqflite_common/src/mixin/platform.dart'; // ignore: implementation_imports +import 'package:sqflite_common_ffi/src/sqflite_ffi_impl.dart'; import 'package:sqlite3/common.dart' as common; import 'package:sqlite3/sqlite3.dart' as ffi; import 'database_tracker.dart'; -import 'sqflite_ffi_handler.dart'; /// Ffi handler. -class _SqfliteFfiHandlerIo with SqfliteFfiHandlerNonImplementedMixin { +class _SqfliteFfiHandlerIo extends SqfliteFfiHandler { /// Opens the database using an ffi implementation @override Future openPlatform(Map argumentsMap) async { @@ -56,20 +54,20 @@ class _SqfliteFfiHandlerIo with SqfliteFfiHandlerNonImplementedMixin { return ffiDb; } - /// Delete the database file including its journal file and other auxiliary files - @override - Future deleteDatabasePlatform(String path) async { - await platform.databaseFileSystem.deleteDatabase(path); - } - - @override - Future readDatabaseBytesPlatform(String path) async { - return platform.databaseFileSystem.readDatabaseBytes(path); + /// Safe delete a files + Future _safeDeleteFile(String path) async { + try { + await File(path).delete(recursive: true); + } catch (_) {} } + /// Delete the database file including its journal file and other auxiliary files @override - Future writeDatabaseBytesPlatform(String path, Uint8List bytes) async { - await platform.databaseFileSystem.writeDatabaseBytes(path, bytes); + Future deleteDatabasePlatform(String path) async { + await _safeDeleteFile(path); + await _safeDeleteFile('$path-wal'); + await _safeDeleteFile('$path-shm'); + await _safeDeleteFile('$path-journal'); } /// Check if database file exists diff --git a/sqflite_common_ffi/lib/src/windows/setup.dart b/sqflite_common_ffi/lib/src/windows/setup.dart index 1d2681c2542eee02af105a7315e866a36f401685..2a5ea3997f7efcf75350fc503f39770f432ed43a 100644 --- a/sqflite_common_ffi/lib/src/windows/setup.dart +++ b/sqflite_common_ffi/lib/src/windows/setup.dart @@ -6,9 +6,6 @@ import 'package:sqflite_common_ffi/src/windows/setup_impl.dart'; import 'package:sqlite3/open.dart'; import 'package:sqlite3/sqlite3.dart'; -/// Local info file name. -const sqflite3InfoJsonFileName = 'sqflite3_info.json'; - /// Get the dll path from our package path. String packageGetSqlite3DllPath(String packagePath) { var path = join(packagePath, 'src', 'windows', 'sqlite3.dll'); diff --git a/sqflite_common_ffi/lib/src/windows/sqlite3.dll b/sqflite_common_ffi/lib/src/windows/sqlite3.dll index 1544c2dbee02632c49352bbe79e077731363a04c..b9fce0d30862342e94785244adad11e6efc14608 100644 Binary files a/sqflite_common_ffi/lib/src/windows/sqlite3.dll and b/sqflite_common_ffi/lib/src/windows/sqlite3.dll differ diff --git a/sqflite_common_ffi/lib/src/windows/sqlite3_info.dart b/sqflite_common_ffi/lib/src/windows/sqlite3_info.dart deleted file mode 100644 index fa3fd7dff32133f0952600e10f249daedb7d5454..0000000000000000000000000000000000000000 --- a/sqflite_common_ffi/lib/src/windows/sqlite3_info.dart +++ /dev/null @@ -1,48 +0,0 @@ -/// Information about the bundled sqlite3.dll -/// https://www.sqlite.org/download.html -class Sqlite3DllInfo { - /// Version string. - final String version; - - /// Src zip. - final String srcZip; - - /// Sha3. - final String sha3; - - /// Sqflite3DllInfo. - Sqlite3DllInfo(this.version, this.srcZip, this.sha3); - - /// Sqflite3DllInfo from map. - factory Sqlite3DllInfo.fromMap(Map map) => Sqlite3DllInfo( - map['version']!.toString(), - map['srcZip']!.toString(), - map['sha3']!.toString()); - - /// To map. - Map toMap() => { - 'version': version, - 'srcZip': srcZip, - 'sha3': sha3, - }; - @override - String toString() => '$version $srcZip $sha3'; -} - -/// 3.38.2 info -var sqlite3_38_2Info = Sqlite3DllInfo( - '3.38.2', - 'https://www.sqlite.org/2022/sqlite-dll-win64-x64-3380200.zip', - '9f71eec9a2c7f12602eaa2af76bd7c052e540502ae7a89dac540e10962e2fa35'); - -// sqlite-dll-win64-x64-3420000.zip -// (1.16 MiB) 64-bit DLL (x64) for SQLite version 3.42.0. -// (SHA3-256: 2425efa95556793a20761dfdab0d3b56a52e61716e8bb65e6a0a3590d41c97c0) -/// 3.42.0 info -var sqlite3_42_0Info = Sqlite3DllInfo( - '3.42.0', - 'https://www.sqlite.org/2023/sqlite-dll-win64-x64-3420000.zip', - '2425efa95556793a20761dfdab0d3b56a52e61716e8bb65e6a0a3590d41c97c0'); - -/// Current info -var sqlite3Info = sqlite3_42_0Info; diff --git a/sqflite_common_ffi/lib/src/windows/sqlite3_info.json b/sqflite_common_ffi/lib/src/windows/sqlite3_info.json deleted file mode 100644 index 24a09eed9d42ef7e871db22db095c7d1c9e53598..0000000000000000000000000000000000000000 --- a/sqflite_common_ffi/lib/src/windows/sqlite3_info.json +++ /dev/null @@ -1 +0,0 @@ -{"version":"3.42.0","srcZip":"https://www.sqlite.org/2023/sqlite-dll-win64-x64-3420000.zip","sha3":"2425efa95556793a20761dfdab0d3b56a52e61716e8bb65e6a0a3590d41c97c0"} \ No newline at end of file diff --git a/sqflite_common_ffi/lib/src/windows/sqlite3_version.md b/sqflite_common_ffi/lib/src/windows/sqlite3_version.md new file mode 100644 index 0000000000000000000000000000000000000000..6594c7e5806f350be51131c3ab56b4d959b9ba2a --- /dev/null +++ b/sqflite_common_ffi/lib/src/windows/sqlite3_version.md @@ -0,0 +1,3 @@ +* v3.38.2 +* https://www.sqlite.org/2022/sqlite-dll-win64-x64-3380200.zip +* sha3: `9f71eec9a2c7f12602eaa2af76bd7c052e540502ae7a89dac540e10962e2fa35` \ No newline at end of file diff --git a/sqflite_common_ffi/pubspec.yaml b/sqflite_common_ffi/pubspec.yaml index 4de6ffe45bcf93b60e65fad46297f043c99ae37c..6ce2ef4de52a915c68b2d61b56c5c896df2d8f9c 100644 --- a/sqflite_common_ffi/pubspec.yaml +++ b/sqflite_common_ffi/pubspec.yaml @@ -1,16 +1,16 @@ name: sqflite_common_ffi homepage: https://github.com/tekartik/sqflite/tree/master/sqflite_common_ffi description: sqflite ffi based implementation, for desktop and units tests. -version: 2.3.0+2 +version: 2.2.5 funding: - https://github.com/sponsors/alextekartik environment: - sdk: '>=3.0.0 <4.0.0' + sdk: '>=2.18.0 <4.0.0' dependencies: sqlite3: '>=1.11.0 <3.0.0' - sqflite_common: '>=2.5.0-1 <4.0.0' + sqflite_common: '>=2.4.5-2 <4.0.0' synchronized: '>=3.0.0 <5.0.0' path: '>=1.8.0 <3.0.0' meta: '>=1.3.0 <3.0.0' diff --git a/sqflite_common_ffi/test/sqflite_ffi_windows_setup_test.dart b/sqflite_common_ffi/test/sqflite_ffi_windows_setup_test.dart index a5984ac6b7131a842423df29aa8d3ba8bfff91e9..aacbeab3b89fd831d9ceea47bf1e606f5bd7e3bd 100644 --- a/sqflite_common_ffi/test/sqflite_ffi_windows_setup_test.dart +++ b/sqflite_common_ffi/test/sqflite_ffi_windows_setup_test.dart @@ -2,13 +2,17 @@ import 'dart:io'; import 'package:archive/archive_io.dart'; +import 'package:http/http.dart'; import 'package:path/path.dart'; import 'package:process_run/shell.dart'; import 'package:sqflite_common_ffi/src/windows/setup.dart'; -import 'package:sqflite_common_ffi/src/windows/sqlite3_info.dart'; import 'package:test/test.dart'; -import '../tool/windows_setup.dart'; +var windowsSqliteVersion = '3.38.2'; +var windowsZipSrc = + 'https://www.sqlite.org/2022/sqlite-dll-win64-x64-3380200.zip'; +var windowsZipSha3 = + '9f71eec9a2c7f12602eaa2af76bd7c052e540502ae7a89dac540e10962e2fa35'; Future computeSha3(String file, {String openssl = 'openssl'}) async { var line = (await run( @@ -41,9 +45,21 @@ Future windowsFindOpenssl() async { } void main() { - var helper = Sqlite3DllSetupHelper(sqlite3Info); - var srcZip = sqlite3Info.srcZip; - var localZip = join('.local', basename(srcZip)); + var localZip = join('.local', basename(windowsZipSrc)); + Future getZip() async { + if (!File(localZip).existsSync()) { + await Directory(dirname(localZip)).create(recursive: true); + try { + await File(localZip) + .writeAsBytes(await readBytes(Uri.parse(windowsZipSrc))); + } catch (e) { + stderr.writeln( + 'Fail to fetch sqlite.zip version $windowsSqliteVersion at $windowsZipSrc'); + return false; + } + } + return true; + } group('sqlite3.dll', () { test('sha3', () async { @@ -53,16 +69,16 @@ void main() { openssl = await windowsFindOpenssl(); } if (openssl != null) { - if (await helper.getZip()) { + if (await getZip()) { var computed = await computeSha3(localZip, openssl: openssl); - expect(computed, sqlite3Info.sha3); + expect(computed, windowsZipSha3); } } }); test('checkDll', () async { var dllPath = findWindowsDllPath()!; - if (await helper.getZip()) { + if (await getZip()) { final inputStream = InputFileStream(localZip); final archive = ZipDecoder().decodeBuffer(inputStream); extractArchiveToDisk(archive, dirname(localZip)); diff --git a/sqflite_common_ffi/test/sqflite_ffi_windows_test.dart b/sqflite_common_ffi/test/sqflite_ffi_windows_test.dart index d494050c6ece5be599bd21e717cd891f751cb328..e9b3598024418a040d1c0a956ca42e18b3d0f87a 100644 --- a/sqflite_common_ffi/test/sqflite_ffi_windows_test.dart +++ b/sqflite_common_ffi/test/sqflite_ffi_windows_test.dart @@ -2,9 +2,10 @@ import 'dart:io'; import 'package:sqflite_common_ffi/sqflite_ffi.dart'; -import 'package:sqflite_common_ffi/src/windows/sqlite3_info.dart'; import 'package:test/test.dart'; +import 'sqflite_ffi_windows_setup_test.dart'; + void main() { if (Platform.isWindows) { sqfliteFfiInit(); @@ -14,7 +15,7 @@ void main() { final results = await db.rawQuery('select sqlite_version()'); var version = results.first.values.first; - expect(version, sqlite3Info.version); + expect(version, windowsSqliteVersion); }); }); } diff --git a/sqflite_common_ffi/tool/windows_setup.dart b/sqflite_common_ffi/tool/windows_setup.dart deleted file mode 100644 index 5685bafd086851b5fa7aa9ce4d29d9177b6dd13f..0000000000000000000000000000000000000000 --- a/sqflite_common_ffi/tool/windows_setup.dart +++ /dev/null @@ -1,97 +0,0 @@ -import 'dart:convert'; -import 'dart:io'; -import 'package:archive/archive_io.dart'; -import 'package:http/http.dart'; -import 'package:path/path.dart'; -import 'package:sqflite_common_ffi/src/windows/setup.dart'; -import 'package:sqflite_common_ffi/src/windows/setup_impl.dart'; -import 'package:sqflite_common_ffi/src/windows/sqlite3_info.dart'; - -class Sqlite3DllSetupHelper { - final Sqlite3DllInfo sqlite3Info; - // This tests does actually the actual install of the dll - - late var srcZip = sqlite3Info.srcZip; - late var localZip = join('.local', basename(srcZip)); - late var localExtractedZipDir = - join('.local', basenameWithoutExtension(srcZip)); - late var localExtractedJsonInfoFile = - join(localExtractedZipDir, sqflite3InfoJsonFileName); - var bundledDir = join('lib', dirname(packageGetSqlite3DllPath('.'))); - late var bundledJsonInfoFilePath = join(bundledDir, 'sqlite3_info.json'); - late var bundledSqlite3DllFilePath = join(bundledDir, 'sqlite3.dll'); - late var localInfoZip = join('.local', basename(srcZip)); - - Sqlite3DllSetupHelper(this.sqlite3Info); - - /// For tools and test only. not exported. - /// Returns null on failure, don't care about the failure... - Future readBundleInfo() async { - try { - var map = pathGetJson(bundledJsonInfoFilePath); - var sqlite3Info = Sqlite3DllInfo.fromMap(map); - print('sqlite3Info $sqlite3Info'); - } catch (_) {} - return null; - } - - Future getZip() async { - if (!File(localZip).existsSync()) { - print('Downloading sqlite3 $sqlite3Info'); - await Directory(dirname(localZip)).create(recursive: true); - try { - await File(localZip).writeAsBytes(await readBytes(Uri.parse(srcZip))); - } catch (e) { - stderr.writeln( - 'Fail to fetch sqlite.zip version $sqlite3_38_2Info at $srcZip'); - return false; - } - } - return true; - } - - Future extractZip() async { - var jsonInfo = File(localExtractedJsonInfoFile); - if (!jsonInfo.existsSync()) { - // Extract the zip - print('Extracting $localZip to $localExtractedZipDir'); - final inputStream = InputFileStream(localZip); - final archive = ZipDecoder().decodeBuffer(inputStream); - extractArchiveToDisk(archive, localExtractedZipDir); - await jsonInfo.writeAsString(jsonEncode(sqlite3Info.toMap())); - } - } - - Future copyToBundle() async { - var srcFile = join(localExtractedZipDir, 'sqlite3.dll'); - var dstFile = bundledSqlite3DllFilePath; - print('Copying $srcZip to $dstFile'); - //await File(dstFile).delete(recursive: true); - await File(srcFile).copy(dstFile); - await File(bundledJsonInfoFilePath) - .writeAsString(jsonEncode(sqlite3Info.toMap())); - //await File() - } -} - -/// This tool is actually ran on linux to download install the updated dll -Future main() async { - await setupSqliteDll(); -} - -Future setupSqliteDll() async { - // Tested only on linux for now. - if (Platform.isLinux) { - var helper = Sqlite3DllSetupHelper(sqlite3Info); - var info = await helper.readBundleInfo(); - if (info?.version != sqlite3Info.version) { - await helper.getZip(); - await helper.extractZip(); - await helper.copyToBundle(); - } else { - print('sqlite3 $sqlite3Info already up to date'); - } - } else { - stderr.writeln('To run on linux!'); - } -} diff --git a/sqflite_common_test/pubspec.yaml b/sqflite_common_test/pubspec.yaml index fb61d7b3170fc46d1186f78bfbf0bce4d3dcc531..61e66d7ae3d6f5227d0c519c60d0de8c7dd7f668 100644 --- a/sqflite_common_test/pubspec.yaml +++ b/sqflite_common_test/pubspec.yaml @@ -4,11 +4,13 @@ version: 0.5.0 publish_to: none environment: - sdk: '>=3.0.0 <4.0.0' + sdk: '>=2.18.0 <4.0.0' dependencies: - sqflite_common_ffi: '>=2.2.0-dev.5 <4.0.0' - sqflite_common: '>=2.4.1-1 <4.0.0' + sqflite_common_ffi: + path: ../sqflite_common_ffi + sqflite_common: + path: ../sqflite_common test: path: synchronized: diff --git a/sqflite_support/pubspec.yaml b/sqflite_support/pubspec.yaml index 44453d709630912f6f84976c3eb784be37d7c2d5..d438527e36b205adaa80a322361228d8e961a376 100644 --- a/sqflite_support/pubspec.yaml +++ b/sqflite_support/pubspec.yaml @@ -5,7 +5,7 @@ homepage: https://github.com/tekartik/sqflite publish_to: none environment: - sdk: '>=3.0.0 <4.0.0' + sdk: '>=2.18.0 <4.0.0' dev_dependencies: lints: '>=1.0.0' diff --git a/sqflite_test_app/pubspec.yaml b/sqflite_test_app/pubspec.yaml index 210fefa0f1cbfb940e6c954b145b9a580291a7fd..a4a8f4ef62255021ac46921e8c9eda720e73bd8b 100644 --- a/sqflite_test_app/pubspec.yaml +++ b/sqflite_test_app/pubspec.yaml @@ -15,7 +15,7 @@ publish_to: none version: 1.1.1 environment: - sdk: '>=3.0.0 <4.0.0' + sdk: '>=2.18.0 <4.0.0' dependencies: # analyzer: '>=5.2.0'