### Flutter App Initialization Source: https://pub.dev/packages/sqfentity/example Standard Flutter application setup including MaterialApp and MyHomePage widgets. This is the root of the application. ```dart import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. // // TRY THIS: Try running your application with "flutter run". You'll see // the application has a blue toolbar. Then, without quitting the app, // try changing the seedColor in the colorScheme below to Colors.green // and then invoke "hot reload" (save your changes or press the "hot // reload" button in a Flutter-supported IDE, or press "r" if you used // the command line to start the app). // // Notice that the counter didn't reset back to zero; the application // state is not lost during the reload. To reset the state, use hot // restart instead. // // This works for code too, not just values: Most code changes can be // tested with just a hot reload. colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks. // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final". final String title; @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { int _counter = 0; void _incrementCounter() { setState(() { // This call to setState tells the Flutter framework that something has // changed in this State, which causes it to rerun the build method below // so that the display can reflect the updated values. If we changed // _counter without calling setState(), then the build method would not be // called again, and so nothing would appear to happen. _counter++; }); } ``` -------------------------------- ### List Playlists of a Track Source: https://pub.dev/packages/sqfentity_gen/changelog This example demonstrates how to retrieve all playlists associated with a specific track, after the models have been generated. ```dart final track = await Track().getById(1); final playlists = await track.getPlaylists().toList(); ``` -------------------------------- ### Initialize Database and Run Samples Source: https://pub.dev/packages/sqfentity_gen/example This function initializes the database and runs a series of sample operations. Ensure the database is initialized correctly on application start. ```dart await runSamples(); ``` -------------------------------- ### Select Products with Pagination Source: https://pub.dev/packages/sqfentity Implement pagination to retrieve a specific page of results. This example fetches the 3rd page with 5 items per page. ```dart Product().select().page(3,5).toList() ``` -------------------------------- ### Select All Products Source: https://pub.dev/packages/sqfentity Example of selecting all rows from the 'product' table without any filters, using `Product().select().toList()`. Displays the first few retrieved products. ```dart flutter EXAMPLE 1.1: SELECT ALL ROWS WITHOUT FILTER ex: SELECT * FROM PRODUCTS flutter -> Product().select().toList() flutter 20 matches found: flutter {id: 1, name: Notebook 12", description: 128 GB SSD i7, price: 6899.0, isActive: true, categoryId: 1, rownum: 0, isDeleted: false} flutter {id: 2, name: Notebook 12", description: 256 GB SSD i7, price: 8244.0, isActive: true, categoryId: 1, rownum: 0, isDeleted: false} flutter {id: 3, name: Notebook 12", description: 512 GB SSD i7, price: 9214.0, isActive: true, categoryId: 1, rownum: 0, isDeleted: false} flutter {id: 4, name: Notebook 13", description: 128 GB SSD, price: 8500.0, isActive: true, categoryId: 1, rownum: 0, isDeleted: false} flutter {id: 5, name: Notebook 13", description: 256 GB SSD, price: 9900.0, isActive: true, categoryId: 1, rownum: 0, isDeleted: false} flutter {id: 6, name: Notebook 13", description: 512 GB SSD, price: 11000.0, isActive: false, categoryId: 1, rownum: 0, isDeleted: false} flutter {id: 7, name: Notebook 15", description: 128 GB SSD, price: 8999.0, isActive: false, categoryId: 1, rownum: 0, isDeleted: false} flutter {id: 8, name: Notebook 15", description: 256 GB SSD, price: 10499.0, isActive: false, categoryId: 1, rownum: 0, isDeleted: false} flutter {id: 9, name: Notebook 15", description: 512 GB SSD, price: 11999.0, isActive: true, categoryId: 1, rownum: 0, isDeleted: false} flutter {id: 10, name: Ultrabook 13", description: 128 GB SSD i5, price: 9954.0, isActive: true, categoryId: 2, rownum: 0, isDeleted: false} flutter {id: 11, name: Ultrabook 13", description: 256 GB SSD i5, price: 11154.0, isActive: true, categoryId: 2, rownum: 0, isDeleted: false} flutter {id: 12, name: Ultrabook 13", description: 512 GB SSD i5, price: 13000.0, isActive: true, categoryId: 2, rownum: 0, isDeleted: false} flutter {id: 13, name: Ultrabook 15", description: 128 GB SSD i7, price: 11000.0, isActive: true, categoryId: 2, rownum: 0, isDeleted: false} flutter {id: 14, name: Ultrabook 15", description: 256 GB SSD i7, price: 12000.0, isActive: true, categoryId: 2, rownum: 0, isDeleted: false} ``` -------------------------------- ### List Tracks of a Playlist Source: https://pub.dev/packages/sqfentity_gen/changelog After generating models, you can retrieve related records. This example shows how to list all tracks associated with a specific playlist. ```dart final playlist = await Playlist().getById(1); final tracks = await playlist.getTracks().toList(); ``` -------------------------------- ### Get Products from Category Source: https://pub.dev/packages/sqfentity Fetches a list of products belonging to a specific category. Iterates through the results to display product details. ```dart final category = await Category().getById(1); final productList = await category.getProducts(); for(var product in productList) { print(product.toMap()); } ``` -------------------------------- ### Add Multiple Products to Database Source: https://pub.dev/packages/sqfentity_gen/example Demonstrates saving multiple product entries to the database using the Product model. Includes examples for different product types and storage capacities. ```dart await Product( name: 'Notebook 13"', description: '128 GB SSD', price: 8500, categoryId: 1, date: DateTime(2020, 01, 04), datetime: DateTime(2020, 01, 04, 15)) .save(); await Product( name: 'Notebook 13"', description: '256 GB SSD', price: 9900, categoryId: 1, date: DateTime(2020, 01, 05), datetime: DateTime(2020, 01, 05, 16)) .save(); await Product( name: 'Notebook 13"', description: '512 GB SSD', price: 11000, categoryId: 1, date: DateTime(2020, 01, 06), datetime: DateTime(2020, 01, 06, 17)) .save(); await Product( name: 'Notebook 15"', description: '128 GB SSD', price: 8999, categoryId: 1, date: DateTime(2020, 01, 07), datetime: DateTime(2020, 01, 07, 18)) .save(); await Product( name: 'Notebook 15"', description: '256 GB SSD', price: 10499, categoryId: 1, date: DateTime(2020, 01, 08), datetime: DateTime(2020, 01, 08, 19)) .save(); await Product( name: 'Notebook 15"', description: '512 GB SSD', price: 11999, categoryId: 1, date: DateTime(2020, 01, 09), datetime: DateTime(2020, 01, 09, 20)) .save(); await Product( name: 'Ultrabook 13"', description: '128 GB SSD i5', price: 9954, categoryId: 2) .save(); await Product( name: 'Ultrabook 13"', description: '256 GB SSD i5', price: 11154, categoryId: 2) .save(); await Product( name: 'Ultrabook 13"', description: '512 GB SSD i5', price: 13000, categoryId: 2) .save(); await Product( name: 'Ultrabook 15"', description: '128 GB SSD i7', price: 11000, categoryId: 2) .save(); await Product( name: 'Ultrabook 15"', description: '256 GB SSD i7', price: 12000, categoryId: 2) .save(); await Product( name: 'Ultrabook 15"', description: '512 GB SSD i7', price: 14000, categoryId: 2) .save(); print('added 15 new products'); // add a few dummy products for delete (id:from 16 to 20) await Product(name: 'Product 1').save(); await Product(name: 'Product 2').save(); await Product(name: 'Product 3').save(); await Product(name: 'Product 4').save(); await Product(name: 'Product 5').save(); print('added 5 dummy products'); } return true; } ``` -------------------------------- ### Syncronize data from the web Source: https://pub.dev/packages/sqfentity This example shows how to synchronize data from a web URL. It first fetches JSON data from a given URL using `Todo.fromWebUrl()`, then saves this data locally using `upsertAll()`, and finally retrieves and prints the first 10 records from the local database. ```APIDOC ## Syncronize data from the web # EXAMPLE 8.2: Fill List from web with Url (JSON data) and saveAll Step 1: Todo.fromWebUrl("URL",(todosList){}) method gets json data from the web and loads into the todosList Step 2: Call Todo().upsertAll(todosList) method saves all data in your local database ```dart todosList = await Todo.fromWebUrl("https://jsonplaceholder.typicode.com/todos"); final results = await Todo().upsertAll(todosList); // print upsert Results for (var res in results) { print(res.toString()); } todosList = await Todo().select().top(10).toList(); print(todosList.length.toString() + " matches found\n"); for (var todo in todosList) { print(todo.toMap()); } ``` ``` -------------------------------- ### Get Product by ID (Method 1) Source: https://pub.dev/packages/sqfentity Fetch a single product record by its ID using the getById() method. ```dart var product = await Product().getById(5); ``` -------------------------------- ### Configure Log Function for Failures Source: https://pub.dev/packages/sqfentity/changelog Example of setting up a log function using the logFunction parameter. This function is called when an insert or update operation fails, allowing for error reporting. ```dart @SqfEntityBuilder(myDbModel) const myDbModel = SqfEntityModel( ... logFunction: getLogFunction, ); getLogFunction(Log log) { // Report the error to the server here } ``` -------------------------------- ### Flutter Build Method Example Source: https://pub.dev/packages/sqfentity/example This is a standard Flutter build method that includes comments explaining its purpose and how it reruns on state changes. It demonstrates basic Scaffold, AppBar, and Column widget usage. ```dart @override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. return Scaffold( appBar: AppBar( // TRY THIS: Try changing the color here to a specific color (to // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar // change color while the other colors stay the same. backgroundColor: Theme.of(context).colorScheme.inversePrimary, // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: Column( // Column is also a layout widget. It takes a list of children and // arranges them vertically. By default, it sizes itself to fit its // children horizontally, and tries to be as tall as its parent. // // Column has various properties to control how it sizes itself and // how it positions its children. Here we use mainAxisAlignment to // center the children vertically; the main axis here is the vertical // axis because Columns are vertical (the cross axis would be // horizontal). // // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint" // action in the IDE, or press "p" in the console), to see the // wireframe for each widget. mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headlineMedium, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } } ``` -------------------------------- ### Define SqfEntity Table with Form Generation Source: https://pub.dev/packages/sqfentity_gen/changelog Example of defining a SqfEntity table with form generation enabled. Includes configuration for table name, primary key, soft deleting, and fields with default values and date range constraints. ```dart @SqfEntityBuilderForm(tableCategory, formListTitleField: 'name', hasSubItems: true) const tableCategory = SqfEntityTable( tableName: 'category', primaryKeyName: 'id', primaryKeyType: PrimaryKeyType.integer_auto_incremental, useSoftDeleting: true, // when useSoftDeleting is true, creates a field named 'isDeleted' on the table, and set to '1' this field when item deleted (does not hard delete) modelName: null, // SqfEntity will set it to TableName automatically when the modelName (class name) is null // declare fields fields: [ SqfEntityField('name', DbType.text), SqfEntityField('isActive', DbType.bool, defaultValue: true), SqfEntityField('date1', DbType.datetime, defaultValue: 'DateTime.now()', minValue: '2019-01-01', maxValue: '2023-01-01'), SqfEntityField('date2', DbType.datetime, minValue: '2020-01-01', maxValue: '2022-01-01') ]); ``` -------------------------------- ### Import sqfentity_gen in Dart code Source: https://pub.dev/packages/sqfentity_gen/install Import the package into your Dart files to start using its functionalities. ```dart import 'package:sqfentity_gen/sqfentity_gen.dart'; ``` -------------------------------- ### Define One-to-One Relationship in SqfEntity Source: https://pub.dev/packages/sqfentity_gen/changelog Example of defining a one-to-one relationship between 'property' and 'product' tables using SqfEntity. Ensure the parent table is correctly referenced. ```dart const tableProductProperties = SqfEntityTable( tableName: 'property', primaryKeyName: 'propertyId', //useSoftDeleting: true, //primaryKeyType: PrimaryKeyType.integer_auto_incremental, fields: [ SqfEntityField('weight', DbType.real), SqfEntityField('stockQty', DbType.numeric), SqfEntityFieldRelationship( //fieldName: 'productId', parentTable: tableProduct, relationType: RelationType.ONE_TO_ONE) ], ); ``` -------------------------------- ### Constraint Violation Results Source: https://pub.dev/packages/sqfentity_gen/changelog Example output showing save failures due to NOT NULL, CHECK, and UNIQUE constraint violations. ```text flutter: -----TEST: NOT NULL CONSTRAINT (name isNotNull) flutter: product-> Save failed. Error: "NOT NULL constraint failed: product.name"... flutter: -----TEST: CHECK CONSTRAINT (price must be greater than 0) flutter: product-> Save failed. Error: "CHECK constraint failed: product"... flutter: -----TEST: UNIQUE CONSTRAINT (name must be UNIQUE) flutter: product-> Save failed. Error: "UNIQUE constraint failed: product.name"... ``` -------------------------------- ### Update Multiple Records by Query (Activate) Source: https://pub.dev/packages/sqfentity Update multiple records that match a specific query. This example shows how to activate products with IDs less than or equal to 10. ```dart Product().select().id.lessThanOrEquals(10).update({"isActive": 1}); ``` -------------------------------- ### Add sqfentity Dependency to Flutter Project Source: https://pub.dev/packages/sqfentity/install Run this command in your terminal to add the sqfentity package to your project's dependencies. This command also implicitly runs 'flutter pub get'. ```bash $ flutter pub add sqfentity ``` -------------------------------- ### Get Category from Product Source: https://pub.dev/packages/sqfentity_gen/example Retrieves a product by its ID and then fetches its associated category object. Handles cases where the product might not exist. ```dart final product = await Product().getById(3); if (product != null) { final category = await product.getCategory(); print( 'EXAMPLE 7.1: goto Category Object from Product \n-> Product.getCategory(); '); print( 'The category of \'${product.name}\' is: ${category == null ? 'null' : category.toMap()}'); } ``` -------------------------------- ### Get Product by ID (Method 2) Source: https://pub.dev/packages/sqfentity Retrieve a single product record by its ID using the fluent select() API with the id.equals() and toSingle() methods. ```dart var product = await Product().select().id.equals(5).toSingle(); ``` -------------------------------- ### Define Default Columns for All Tables Source: https://pub.dev/packages/sqfentity/changelog Example of defining default columns for all tables in a database model using the defaultColumns parameter. This ensures that specified columns are added to every table. ```dart @SqfEntityBuilder(myDbModel) const myDbModel = SqfEntityModel( modelName: 'AppDatabase', databaseName: 'AppDatabase.db', databaseTables: [ table1, table2 ], sequences: [seqIdentity], bundledDatabasePath: null, defaultColumns: const [ SqfEntityField('lastUpdate', DbType.datetime), ]); ``` -------------------------------- ### Filter with Brackets and OR Conditions (2) Source: https://pub.dev/packages/sqfentity Selects specific fields and applies filtering with brackets for OR conditions, combined with AND. This example demonstrates filtering by price range and description patterns. ```dart await Product().select(columnsToSelect:["name","price"]) .price.lessThanOrEquals(10000) .and.startBlock.description.contains("128").or.description.endsWith("GB").endBlock .toList() ``` -------------------------------- ### Complex Filter with Brackets Source: https://pub.dev/packages/sqfentity_gen/example Retrieves a single product where the price is greater than 10000 AND (description contains '256' OR description starts with '512'). This is equivalent to `SELECT TOP 1 * FROM PRODUCTS WHERE price>10000 AND (description LIKE '%256%' OR description LIKE '512%')`. ```dart final singleProduct = await Product() .select() .price .greaterThan(10000) .and .startBlock .description .contains('256') .or .description .startsWith('512') .endBlock .toSingle(); print( 'EXAMPLE 1.6: BRACKETS ex: SELECT TOP 1 * FROM PRODUCTS WHERE price>10000 AND (description LIKE \'%256\'% OR description LIKE \'512%\') -> Product().select().price.greaterThan(10000).and.startBlock.description.contains(\'256\').or.description.startsWith(\'512\"').endBlock.toSingle((product){ // TO DO }) '); print('Toplam ${(singleProduct != null ? '1' : '0')} sonuç listeleniyor:'); if (singleProduct != null) { print(singleProduct.toMap()); } print('--------------------------------------------------------------- '); ``` -------------------------------- ### Complex Filter with AND, OR, and Brackets Source: https://pub.dev/packages/sqfentity Construct complex queries using `and`, `or`, `startBlock`, and `endBlock` to replicate SQL's use of parentheses for logical grouping. This example filters products by price and a combination of description conditions. ```Dart Product().select().price.greaterThan(10000).and.startBlock.description.contains("256").or.description.startsWith("512").endBlock.toSingle((product){ // TO DO }) ``` -------------------------------- ### Select Distinct Product Names Source: https://pub.dev/packages/sqfentity Use the `distinct` method to retrieve unique values from a specific column. This is useful for getting a list of all available product names, for example. ```dart Product().distinct(columnsToSelect:["name"]).price.greaterThan(3000).toList(); ``` -------------------------------- ### Initialize SqfEntity Tables Source: https://pub.dev/packages/sqfentity Logs the successful initialization of SqfEntity tables for 'category', 'product', and 'todos'. This indicates the database schema is ready. ```dart flutter >>>>>>>>>>>>>>>>>>>>>>>>>>>> SqfEntityTable of 'category' initialized successfuly flutter >>>>>>>>>>>>>>>>>>>>>>>>>>>> SqfEntityTable of 'product' initialized successfuly flutter >>>>>>>>>>>>>>>>>>>>>>>>>>>> SqfEntityTable of 'todos' initialized successfuly ``` -------------------------------- ### Database and Table Initialization Source: https://pub.dev/packages/sqfentity Confirms the creation of the SqfEntity database and successful initialization of tables like 'product', 'category', and 'todos'. It also shows index creation for tables. ```dart flutter sampleORMx01.db created successfully flutter SQFENTITIY: Table named 'product' was initialized successfuly with create new table flutter SQFENTITIY: alterTableIndexesQuery => [CREATE INDEX IF NOT EXISTS IDXCategorycategoryId ON product (categoryId ASC)] flutter SQFENTITIY: Table named 'category' was initialized successfuly with create new table flutter SQFENTITIY: Table named 'todos' was initialized successfuly with create new table flutter SQFENTITIY: The database is ready for use ``` -------------------------------- ### Identity Sequence Operations Source: https://pub.dev/packages/sqfentity Demonstrates operations for managing identity sequences, including getting the current value, getting the next value, and resetting the sequence. ```dart final currentVal= await IdentitySequence().currentVal(); // result: currentVal = 9 final nextVal = await IdentitySequence().nextVal(); // result: nextVal = 10 final int nextVal2 = await IdentitySequence().nextVal(); // result: nextVal2 = 0 final int currentVal2 = await IdentitySequence().currentVal(); // result: currentVal2 = 0 final int currentVal3 = await IdentitySequence().reset(); // result: currentVal3 = 0 ``` -------------------------------- ### Get Identity Sequence Current and Next Values Source: https://pub.dev/packages/sqfentity_gen/example Demonstrates how to get the current and next values from an identity sequence using `currentVal()` and `nextVal()`. This is useful for generating unique identifiers. ```dart final currentVal = await IdentitySequence().currentVal(); final nextVal = await IdentitySequence().nextVal(); final nextVal2 = await IdentitySequence().nextVal(); final currentVal2 = await IdentitySequence().currentVal(); print('Sample Code:\n'); print(''' final currentVal= await IdentitySequence().currentVal(); result: currentVal = $currentVal final nextVal = await IdentitySequence().nextVal(); result: nextVal = $nextVal final int nextVal2 = await IdentitySequence().nextVal(); result: nextVal2 = $nextVal2 final int currentVal2 = await IdentitySequence().currentVal(); result: currentVal2 = $currentVal2 '''); ``` -------------------------------- ### Defining a Sample Table with Constraints Source: https://pub.dev/packages/sqfentity/changelog Defines a sample 'product' table using SqfEntityTable, specifying primary key and fields with constraints like uniqueness, not null, indexing, default values, and check conditions. ```dart const tableProduct = SqfEntityTable( tableName: 'product', primaryKeyName: 'id', primaryKeyType: PrimaryKeyType.integer_auto_incremental, fields: [ SqfEntityField('name', DbType.text, isUnique: true, isNotNull: true, isIndex:true), SqfEntityField('price', DbType.real, defaultValue: 1, checkCondition: '(this)>0'), ], ); ``` -------------------------------- ### Get Category from Product Source: https://pub.dev/packages/sqfentity Retrieves the associated category for a given product. Ensure the Product object is fetched first. ```dart final product = await Product().getById(1); final category = await product.getCategory(); print(category.toMap()); ``` -------------------------------- ### Create a Database Model with SqfEntityModel Source: https://pub.dev/packages/sqfentity Instantiate SqfEntityModel to define your database structure, including tables, forms, and sequences. Supports multiple databases. ```dart @SqfEntityBuilder(myDbModel) const myDbModel = SqfEntityModel( modelName: 'MyDbModel', // optional databaseName: 'sampleORM.db', password: null, // You can set a password if you want to use crypted database // (For more information: https://github.com/sqlcipher/sqlcipher) // put defined tables into the tables list. databaseTables: [tableCategory, tableProduct, tableTodo], // You can define tables to generate add/edit view forms if you want to use Form Generator property formTables: [tableProduct, tableCategory, tableTodo], // put defined sequences into the sequences list. sequences: [seqIdentity], bundledDatabasePath: null // 'assets/sample.db' // This value is optional. When bundledDatabasePath is empty then EntityBase creats a new database when initializing the database ); ``` -------------------------------- ### Get Category from Product Source: https://pub.dev/packages/sqfentity Retrieves the associated category object for a given product. This demonstrates navigating one-to-one or many-to-one relationships. ```dart Product.getCategory(); ``` -------------------------------- ### Create Model from Existing Database Source: https://pub.dev/packages/sqfentity_gen/example This function demonstrates how to convert an existing SQLite database into SQFEntity models. Ensure the database file is placed in the `assets` folder and declared in `pubspec.yaml`. ```dart Future createModelFromDatabaseSample() async { /* STEP 1 // Copy your database in /assets folder (in this sample we copied chinook.sqlite database) // and define your asset database in pubspec.yaml as below flutter: assets: - assets/chinook.sqlite */ // STEP 2 // Run this script with this parameters. // databaseName: Specify a name for your database to use for the database connection // bundledDatabasePath: File path of your copied database final bundledDbModel = await convertDatabaseToModelBase(BundledDbModel() ..databaseName = 'chinook.db' ..bundledDatabasePath = 'assets/chinook.sqlite'); // STEP 3 // Run this function to convert the model to annotation final String modelConstString = SqfEntityConverter(bundledDbModel).createConstDatabase(); // That's all. Set clipboard to paste codes await Clipboard.setData(ClipboardData(text: modelConstString)); /* Model were created successfully and set to the Clipboard. STEP 1: Open model.dart file in lib/model folder and paste (Ctrl+V) models after following line part 'model.g.view.dart'; STEP 2: Go Terminal Window and run command below flutter pub run build_runner build --delete-conflicting-outputs Your Entity models will be created in lib/model/model.g.dart */ print('''Your ${bundledDbModel.databaseName} were created successfully and set to the Clipboard. STEP 1: Open model.dart file in lib/model folder and paste models after following line part 'model.g.dart'; STEP 2: Go Terminal Window and run command below flutter pub run build_runner build --delete-conflicting-outputs Your Entity models will be created in lib/model/model.g.dart'''); return modelConstString; } ``` -------------------------------- ### SqfEntity Identity Sequence Operations Source: https://pub.dev/packages/sqfentity Demonstrates the usage of IdentitySequence for managing sequence values, including getting current, next, and resetting the sequence. ```dart final int currentVal = await IdentitySequence().currentVal(); final int nextVal = await IdentitySequence().nextVal(); final int nextVal2 = await IdentitySequence().nextVal(); final int currentVal2 = await IdentitySequence().currentVal(); // You can reset sequence anytime final int currentVal3 = await IdentitySequence().reset(); print(""" IdentitySequence().currentVal = $currentVal IdentitySequence().nextVal = $nextVal IdentitySequence().nextVal = $nextVal2 IdentitySequence().currentVal = $currentVal2 IdentitySequence().reset = $currentVal3 // returns start value """); ``` -------------------------------- ### Get and Update a Single Record Source: https://pub.dev/packages/sqfentity_gen/example Retrieve a single record by its ID using `getById` and then update its properties before saving the changes with the `save` method. ```dart final product2 = await Product().getById(15); // TO DO // update product object if exist if (product2 != null) { product2.description = '512GB SSD i7 (updated)'; await product2.save(); print( 'EXAMPLE 5.3: id=15 Product item updated: ${product2.toMap().toString()}'); } else { print('EXAMPLE 5.3: id=15 => product not found'); } ``` -------------------------------- ### Define Database Tables and Sequences with SqfEntity Source: https://pub.dev/packages/sqfentity_base/example Define your database tables and sequences using SqfEntity constants. This includes specifying table names, primary keys, field types, default values, relationships, and sequences. Ensure you import the necessary packages. ```dart // STEP 1: import sqfentity package. import 'package:sqfentity/sqfentity.dart'; import 'package:sqfentity_base/sqfentity_base.dart'; // STEP 1: define your tables as shown in the example Classes below. // Define the 'TableCategory' constant as SqfEntityTable. const tableCategory = SqfEntityTable( tableName: 'category', primaryKeyName: 'id', primaryKeyType: PrimaryKeyType.integer_auto_incremental, useSoftDeleting: true, // when useSoftDeleting is true, creates a field named 'isDeleted' on the table, and set to '1' this field when item deleted (does not hard delete) modelName: null, // SqfEntity will set it to TableName automatically when the modelName (class name) is null // declare fields fields: [ SqfEntityField('name', DbType.text), SqfEntityField('isActive', DbType.bool, defaultValue: true), ]); // Define the 'TableProduct' constant as SqfEntityTable. const tableProduct = SqfEntityTable( tableName: 'product', primaryKeyName: 'id', primaryKeyType: PrimaryKeyType.integer_auto_incremental, useSoftDeleting: true, fields: [ SqfEntityField('name', DbType.text), SqfEntityField('description', DbType.text), SqfEntityField('price', DbType.real, defaultValue: 0), SqfEntityField('isActive', DbType.bool, defaultValue: true), SqfEntityFieldRelationship( parentTable: tableCategory, deleteRule: DeleteRule.CASCADE, defaultValue: '0'), // Relationship column for CategoryId of Product SqfEntityField('rownum', DbType.integer, sequencedBy: seqIdentity /*Example of linking a column to a sequence */), SqfEntityField('imageUrl', DbType.text) ]); // Define the 'Todo' constant as SqfEntityTable. const tableTodo = SqfEntityTable( tableName: 'todos', primaryKeyName: 'id', useSoftDeleting: false, // when useSoftDeleting is true, creates a field named 'isDeleted' on the table, and set to '1' this field when item deleted (does not hard delete) primaryKeyType: PrimaryKeyType.integer_unique, defaultJsonUrl: 'https://jsonplaceholder.typicode.com/todos', // optional: to synchronize your table with json data from webUrl // declare fields fields: [ SqfEntityField('userId', DbType.integer), SqfEntityField('title', DbType.text), SqfEntityField('completed', DbType.bool, defaultValue: false) ]); // Define the 'identity' constant as SqfEntitySequence. const seqIdentity = SqfEntitySequence( sequenceName: 'identity', maxValue: 10000, /* optional. default is max int (9.223.372.036.854.775.807) */ //modelName: 'SQEidentity', /* optional. SqfEntity will set it to sequenceName automatically when the modelName is null*/ //cycle : false, /* optional. default is false; */ //minValue = 0; /* optional. default is 0 */ //incrementBy = 1; /* optional. default is 1 */ // startWith = 0; /* optional. default is 0 */ ); // STEP 2: Create your Database Model constant instanced from SqfEntityModel // Note: SqfEntity provides support for the use of multiple databases. So you can create many Database Models and use them in the application. @SqfEntityBuilder(myDbModel) const myDbModel = SqfEntityModel( modelName: null, databaseName: 'sampleORM.db', // put defined tables into the tables list. databaseTables: [tableCategory, tableProduct, tableTodo], // put defined sequences into the sequences list. sequences: [seqIdentity], bundledDatabasePath: null // 'assets/sample.db' // This value is optional. When bundledDatabasePath is empty then EntityBase creats a new database when initializing the database ); /* STEP 3: That's All.. --> Go Terminal Window and run command below flutter pub run build_runner build --delete-conflicting-outputs Note: After running the command Please check lib/model/model.g.dart Enjoy.. Huseyin TOKPINAR */ void main(List args) async { // Run Entity Model samples // ATTENTION! when the software/app is started, you must check the database was it initialized. // If needed, initilizeDb method runs CREATE / ALTER TABLE query for you. final bool isInitialized = await MyDbModel().initializeDB(); if (isInitialized == false) { // If the database is not initialized, something went wrong. Check DEBUG CONSOLE for alerts // TO DO return; } } class MyDbModel extends SqfEntityModelProvider{ } ``` -------------------------------- ### Filter with NOT Keyword Source: https://pub.dev/packages/sqfentity Excludes records that meet a specified condition using the 'NOT' keyword. This example excludes products with an ID greater than 5. ```dart await Product().select().id.not.greaterThan(5).toList() ``` -------------------------------- ### List Products of a Category Source: https://pub.dev/packages/sqfentity_gen/example Fetches all categories and then lists the products associated with each category. Prints the count and details of products for each category. ```dart final categoryList = await Category().select().toList(); for (var category in categoryList) { final productList = await category.getProducts()!.toList(); print( 'EXAMPLE 7.2.${category.id}: Products of \'${category.name}\' listing \n-> category.getProducts((productList) {}); '); // PRINT RESULTS TO DEBUG CONSOLE print('${productList.length} matches found:'); for (int i = 0; i < productList.length; i++) { print(productList[i].toMap()); } print('---------------------------------------------------------------'); return; } return; ``` -------------------------------- ### Declare SqfEntityFieldVirtual for Virtual Property Source: https://pub.dev/packages/sqfentity_gen/changelog Example of declaring a virtual field 'fullName' in a model. This field is generated in the model class but not in the database table. ```dart const tablePerson = SqfEntityTable( tableName: 'person', primaryKeyName: 'id', primaryKeyType: PrimaryKeyType.integer_auto_incremental, fields: [ SqfEntityField('firstName', DbType.text), SqfEntityField('lastName', DbType.text), SqfEntityFieldVirtual('fullName', DbType.text), ], customCode: ''' init() { fullName = '\'firstName \'lastName'; } ''' ); ``` -------------------------------- ### Select Products by Price, Name, and Description Source: https://pub.dev/packages/sqfentity_gen/example Retrieves a list of products filtered by price range, name containment, and description containment. Useful for searching products with specific criteria. ```dart productList = await Product() .select() .price .between(minPrice, maxPrice) .and .name .contains(nameContains) .and .description .contains(descriptionContains) .toList(); ``` -------------------------------- ### Preload Child Products in Category Source: https://pub.dev/packages/sqfentity_gen/changelog Demonstrates how to preload 'plProducts' for a Category using the 'preloadFields' parameter. Accessing preloaded products is shown. ```dart final category = await Category().select()..(your optional filter)...toSingle(preload:true, preloadFields: ['plProducts']); // you can see pre-loaded products of this category category.plProducts[0].name ``` -------------------------------- ### Import Existing SQLite Database Source: https://pub.dev/packages/sqfentity Import an existing SQLite database by copying it to the assets folder and configuring pubspec.yaml. Then, use convertDatabaseToModelBase to generate the model. ```dart class BundledDbModel extends SqfEntityModelProvider {} final bundledDbModel = await convertDatabaseToModelBase(BundledDbModel() ..databaseName = 'chinook.db' ..bundledDatabasePath = 'assets/chinook.sqlite'); ``` -------------------------------- ### Todo.fromWebUrl and upsertAll Source: https://pub.dev/packages/sqfentity Fetches a list of todos from a specified URL and upserts them into the database. This is useful for directly loading data from a remote JSON endpoint. ```APIDOC ## Todo.fromWebUrl and upsertAll ### Description Fetches a list of todos from a specified URL and upserts them into the database. This is useful for directly loading data from a remote JSON endpoint. ### Method ``` Todo.fromWebUrl("https://jsonplaceholder.typicode.com/todos", (todosList) { ... }) await Todo().upsertAll(todosList); ``` ### Parameters * `url` (String) - The URL to fetch the JSON data from. * `todosList` (List) - A list of Todo objects to be upserted. ``` -------------------------------- ### Execute Custom SQL Query and Get DataTable Source: https://pub.dev/packages/sqfentity Executes a custom SQL SELECT query and returns the results as a List of Maps, where each Map represents a row. ```dart MyDbModel().execDataTable('SELECT name, price FROM product order by price desc LIMIT 5'); // print result: // {name: Ultrabook 15", price: 14000.0} // {name: Ultrabook 13", price: 13000.0} // {name: Ultrabook 15", price: 12000.0} // {name: Notebook 15", price: 11999.0} // {name: Ultrabook 13", price: 11154.0} ``` -------------------------------- ### Preload Parent Category in Product Source: https://pub.dev/packages/sqfentity_gen/changelog Demonstrates how to preload the parent 'plCategory' for Products. Accessing the preloaded category data for each product is shown. ```dart final products = await Product().select().toList(preload:true); // you see pre-loaded categories of all products products[0].plCategory.name ``` -------------------------------- ### Synchronize Data from Web URL and Save Source: https://pub.dev/packages/sqfentity Fetches JSON data from a web URL, loads it into a list, and then saves all items to the local database using upsertAll(). Finally, it retrieves and prints the first 10 records from the local database. ```dart todosList = await Todo.fromWebUrl("https://jsonplaceholder.typicode.com/todos"); final results = await Todo().upsertAll(todosList); // print upsert Results for (var res in results) { print(res.toString()); } todosList = await Todo().select().top(10).toList(); print(todosList.length.toString() + " matches found\n"); for (var todo in todosList) { print(todo.toMap()); } ``` -------------------------------- ### Run Build Runner for Model Generation Source: https://pub.dev/packages/sqfentity Execute the build_runner command to generate model files after defining your database model. ```bash flutter pub run build_runner build --delete-conflicting-outputs ``` -------------------------------- ### DELETE multiple records with query Source: https://pub.dev/packages/sqfentity This section illustrates how to delete multiple records from the database that match a given query. The example provided deletes all products with an ID greater than 17. ```APIDOC ## DELETE multiple records with query # EXAMPLE 6.4: DELETE PRODUCT WHERE ID>17 ```dart final result = await Product().select().id.greaterThan(17).delete(); print(result.toString()); ``` ``` -------------------------------- ### Create Multiple Product Records Quickly Source: https://pub.dev/packages/sqfentity Efficiently add multiple product records using the withFields() constructor for quick data entry. ```dart await Product.withFields( "Notebook 12\"", "128 GB SSD i7", 6899, true, notebookCategoryId, 0, false).save(); await Product.withFields( "Notebook 12\"", "256 GB SSD i7", 8244, true, notebookCategoryId, 0, false).save(); await Product.withFields( "Notebook 12\"", "512 GB SSD i7", 9214, true, notebookCategoryId, 0, false).save(); await Product.withFields( "Notebook 13\"", "128 GB SSD", 8500, true, notebookCategoryId, 0, false).save(); await Product.withFields( "Notebook 13\"", "256 GB SSD", 9900, true, notebookCategoryId, 0, false).save(); await Product.withFields( "Notebook 13\"", "512 GB SSD", 11000, null, notebookCategoryId, 0, false).save(); await Product.withFields( "Notebook 15\"", "128 GB SSD", 8999, null, notebookCategoryId, 0, false).save(); await Product.withFields( "Notebook 15\"", "256 GB SSD", 10499, null, notebookCategoryId, 0, false).save(); await Product.withFields( "Notebook 15\"", "512 GB SSD", 11999, true, notebookCategoryId, 0, false).save(); await Product.withFields( "Ultrabook 13\"", "128 GB SSD i5", 9954, true, ultrabookCategoryId, 0, false).save(); await Product.withFields( "Ultrabook 13\"", "256 GB SSD i5", 11154, true, ultrabookCategoryId, 0, false).save(); await Product.withFields( "Ultrabook 13\"", "512 GB SSD i5", 13000, true, ultrabookCategoryId, 0, false).save(); await Product.withFields( "Ultrabook 15\"", "128 GB SSD i7", 11000, true, ultrabookCategoryId, 0, false).save(); await Product.withFields( "Ultrabook 15\"", "256 GB SSD i7", 12000, true, ultrabookCategoryId, 0, false).save(); await Product.withFields( "Ultrabook 15\"", "512 GB SSD i7", 14000, true, ultrabookCategoryId, 0, false).save(); ``` -------------------------------- ### Import necessary packages for SqfEntity model Source: https://pub.dev/packages/sqfentity Import required packages for SqfEntity model definition and Flutter development. ```dart import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; import 'package:http/http.dart' as http; import 'package:flutter/material.dart'; import 'package:sqfentity/sqfentity.dart'; import 'package:sqfentity_gen/sqfentity_gen.dart'; import '../tools/helper.dart'; import 'view.list.dart'; ``` -------------------------------- ### Select Products Between Datetimes Source: https://pub.dev/packages/sqfentity_gen/example Filters products based on a datetime range. Note: The example uses a string-based WHERE clause for datetime comparison, which might require specific database formatting. ```dart productList = await Product() .select() .where( 'datetime BETWEEN \'${DateTime(2020, 1, 1, 14)}\' AND \'${DateTime(2020, 1, 1, 14).millisecondsSinceEpoch}\'') .toList(); ```