import '../../all_imports.dart';
import 'package:path/path.dart' as p;
class DatabaseHelper {
static final DatabaseHelper instance = DatabaseHelper._();
late Database _database;
late Database _newDatabase;
bool _isInitialized = false;
bool _isInitializedNew = false;
String? dbPath;
String? newdbpath;
DatabaseHelper._();
Future get database async {
if (_database.isOpen) return _database;
code
if (!_isInitialized) {
await initialize();
}
return _database;
}
Future get newDatabase async {
if (_newDatabase.isOpen) return _newDatabase;
code
if (!_isInitializedNew) {
await initializeNewDB();
}
return _newDatabase;
}
Future initialize() async {
if (_isInitialized) return;
code
if (kIsWeb) {
databaseFactory = databaseFactoryFfiWeb;
} else if (Platform.isLinux || Platform.isWindows) {
// Use the ffi version on linux and windows
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
}
// Get a location using getDatabasesPath
var databasesPath = await getDatabasesPath();
String path = p.join(databasesPath, database_name);
dbPath = path;
var sqliteLib = await databaseFactory.openDatabase(path,
options: OpenDatabaseOptions(
version: 2,
onCreate: _onCreate,
onUpgrade: _onUpdate
));
_onCreate(sqliteLib, 1);
_onUpdate(sqliteLib, 1,2);
_database = sqliteLib;
_isInitialized = true;
}
Future initializeNewDB() async {
if (_isInitializedNew) return;
code
Assistant
if (kIsWeb) {
databaseFactory = databaseFactoryFfiWeb;
} else if (Platform.isLinux || Platform.isWindows) {
// Use the ffi version on linux and windows
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
}
// Get a location using getDatabasesPath
var databasesPath = await getDatabasesPath();
String path = p.join(databasesPath, new_database_name);
newdbpath = path;
var sqliteLib = await databaseFactory.openDatabase(path,
options: OpenDatabaseOptions(
version: 1,
onCreate: _onCreateNewDB,
onUpgrade: _onUpdateNewDB
));
_onCreateNewDB(sqliteLib, 1);
_onUpdateNewDB(sqliteLib, 1,2);
_newDatabase = sqliteLib;
_isInitializedNew = true;
}
Future _onCreate(Database db, int version) async {
}
Future _onUpdate(Database db, int oldVersion, int newVersion) async {
if (oldVersion < 2) {
// You can perform any necessary actions here, even if there are no schema changes.
await db.execute('ALTER TABLE orderhistorytableDROPCOLUMNisshipment′);varresult=awaitdb.rawQuery(′PRAGMAtableinfo(order_history_table)');
print("Columns in $order_history_table");
for (var row in result) {
print(row['name']); // Prints each column name
}
// Update the database version to the new version.
//await db.updateVersion(newVersion);
}
}
Future _onUpdateNewDB(Database db, int oldVersion, int newVersion) async {
if (oldVersion < newVersion) {
// You can perform any necessary actions here, even if there are no schema changes.
code
// Update the database version to the new version.
//await db.updateVersion(newVersion);
}
}
}
Future orderHistoryTable(Database db) async {
await db.execute('''
CREATE TABLE IF NOT EXISTS $order_history_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT,
repId TEXT,
orderId TEXT,
accountNo TEXT,
accountName TEXT,
doorwayId TEXT,
shipTo TEXT,
street TEXT,
city TEXT,
state TEXT,
zip TEXT,
quantity TEXT,
status TEXT
)
''');
} /// TrackingNumberChanges=>Add Tracking number in order history table.
Future usersTable(Database db) async {
await db.execute('''
CREATE TABLE IF NOT EXISTS $user_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
odataContext TEXT,
displayName TEXT,
givenName TEXT,
jobTitle TEXT,
mail TEXT,
mobilePhone TEXT,
officeLocation TEXT,
preferredLanguage TEXT,
surname TEXT,
userPrincipalName TEXT,
userId TEXT
code
)
''');
}
Future cartDetailsTable(Database db) async {
await db.execute('''
CREATE TABLE IF NOT EXISTS $cart_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
brand TEXT,
indication TEXT,
drawer TEXT,
lensKey TEXT,
lensValue TEXT,
qty INTEGER,
customerId TEXT,
axis TEXT,
highAdd TEXT,
lowAdd TEXT,
sku TEXT,
cyl TEXT,
range TEXT
)
''');
}
Future orderHistoryDetailTable(Database db) async {
await db.execute('''
CREATE TABLE IF NOT EXISTS $orderhistory_detail_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
orderId TEXT,
brand TEXT,
indication TEXT,
drawer TEXT,
lensKey TEXT,
lensValue TEXT,
qty INTEGER,
customerId TEXT,
axis TEXT,
highAdd TEXT,
lowAdd TEXT,
sku TEXT,
cyl TEXT,
range TEXT
)
''');
}
Future outsideFitLensTable(Database db) async {
await db.execute('''
CREATE TABLE IF NOT EXISTS $outside_fit_lens_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sku TEXT,
brand TEXT,
indication TEXT,
power TEXT,
cylinder TEXT,
axis TEXT,
qty INTEGER,
addValue TEXT
)
''');
}
Future topDachCabinetComponentTable(Database db) async {
await db.execute('''
CREATE TABLE IF NOT EXISTS $topdach_cabinet_component_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sku TEXT,
componentid TEXT
)
''');
}
Future copyDataToNewDatabase(Database _database, Database _newDatabase) async {
// Copy data from orderHistoryTable
List<Map<String, dynamic>> orderHistoryData = await _database.query(order_history_table);
for (var newRow in orderHistoryData) {
await _newDatabase.insert(order_history_table, newRow, conflictAlgorithm: ConflictAlgorithm.replace);
}
List<Map<String, dynamic>> orderHistoryDetailData = await _database.query(orderhistory_detail_table);
for (var newRow in orderHistoryDetailData) {
await _newDatabase.insert(orderhistory_detail_table, newRow, conflictAlgorithm: ConflictAlgorithm.replace);
}
}
its shows this debugs console
E/SQLiteLog( 3256): (1) no such column: "isshipment" in "ALTER TABLE order_history DROP COLUMN isshipment"
I/flutter ( 3256): Columns in order_history
I/flutter ( 3256): id
I/flutter ( 3256): date
I/flutter ( 3256): repId
I/flutter ( 3256): orderId
I/flutter ( 3256): accountNo
I/flutter ( 3256): accountName
I/flutter ( 3256): doorwayId
I/flutter ( 3256): shipTo
I/flutter ( 3256): street
I/flutter ( 3256): city
I/flutter ( 3256): state
I/flutter ( 3256): zip
I/flutter ( 3256): quantity
I/flutter ( 3256): status
E/flutter ( 3256): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(no such column: "isshipment" (code 1 SQLITE_ERROR): , while compiling: ALTER TABLE order_history DROP COLUMN isshipment) sql 'ALTER TABLE order_history DROP COLUMN isshipment' args []
E/flutter ( 3256): #0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7)
E/flutter ( 3256):
E/flutter ( 3256): #1 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:33:16)
E/flutter ( 3256):
E/flutter ( 3256): #2 SqfliteDatabaseMixin.txnSynchronized (package:sqflite_common/src/database_mixin.dart:517:14)
E/flutter ( 3256):
E/flutter ( 3256): #3 DatabaseHelper._onUpdate (package:trialOrderPro/data/helper/database_helper.dart:123:7)
E/flutter ( 3256):
E/flutter ( 3256):
E/SQLiteLog( 3256): (1) table order_history has no column named isshipment in "INSERT OR REPLACE INTO order_history (id, date, repId, orderId, accountNo, accountName, doorwayId, shipTo, street, city, state, zip, quantity, status, iss
E/flutter ( 3256): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(table order_history has no column named isshipment (code 1 SQLITE_ERROR): , while compiling: INSERT OR REPLACE INTO order_history (id, date, repId, orderId, accountNo, accountName, doorwayId, shipTo, street, city, state, zip, quantity, status, isshipment) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)) sql 'INSERT OR REPLACE INTO order_history (id, date, repId, orderId, accountNo, accountName, doorwayId, shipTo, street, city, state, zip, quantity, status, isshipment) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' args [1, Nov 08, 2024T13:27:512, sandeep.chandekar, BL_SA_292618270, , DR Faith Chang, 14896, , 3901 Main St Ste 602, Flushing, NY, 11354-5482, 3, PENDING, ]
E/flutter ( 3256): #0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7)
E/flutter ( 3256):
E/flutter ( 3256): #1 SqfliteDatabaseMixin.txnRawInsert. (package:sqflite_common/src/database_mixin.dart:576:14)
E/flutter ( 3256):
E/flutter ( 3256): #2 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:33:16)
E/flutter ( 3256):
E/flutter ( 3256): #3 SqfliteDatabaseMixin.txnSynchronized (package:sqflite_common/src/database_mixin.dart:517:14)
E/flutter ( 3256):
E/flutter ( 3256): #4 copyDataToNewDatabase (package:trialOrderPro/data/helper/database_helper.dart:291:7)
E/flutter ( 3256):
E/flutter ( 3256): #5 AwsController.downloadOrderHistorDatabaseFile (package:trialOrderPro/modules/cart/controllers/aws_s3_controller.dart:127:5)
E/flutter ( 3256):
E/flutter ( 3256): #6 OrderHistoryListControllerGetX.syncOrderHistory (package:trialOrderPro/modules/order_history/controllers/order_history_list_screen_controller.dart:146:8)
E/flutter ( 3256):
The errors you're encountering are due to the fact that your code is attempting to manipulate a column ("isshipment") that doesn't exist in your database schema. Specifically:
Altering the Table to Drop a Non-existent Column:
The first error occurs when you try to execute:
dart
await db.execute('ALTER TABLE $order_history_table DROP COLUMN isshipment');
However, the isshipment column does not exist in your order_history table, leading to the error:
code
no such column: "isshipment" in "ALTER TABLE order_history DROP COLUMN isshipment"
Inserting Data with a Non-existent Column:
The second error occurs when you try to insert data that includes the isshipment column into the order_history table. Since the table doesn't have this column, SQLite throws an error:
code
table order_history has no column named isshipment
Why This is Happening:
Missing Column: Your order_history table creation script doesn't include the isshipment column. Therefore, any operation that references this column will fail.
SQLite Limitations: Older versions of SQLite (before 3.35.0) do not support the ALTER TABLE DROP COLUMN syntax. Even if they did, trying to drop a column that doesn't exist will cause an error.
Solutions:
Check if Column Exists Before Dropping It:
Modify your _onUpdate function to check if the isshipment column exists before attempting to drop it. Here's how you can do it:
dart
Future _onUpdate(Database db, int oldVersion, int newVersion) async {
if (oldVersion < 2) {
// Check if column 'isshipment' exists
var result = await db.rawQuery('PRAGMA table_info($order_history_table)');
List<String> columns = result.map((row) => row['name'] as String).toList();
if (columns.contains('isshipment')) {
// Column exists, proceed to drop it
try {
await db.execute('ALTER TABLE $order_history_table DROP COLUMN isshipment');
} catch (e) {
print('Error dropping column isshipment: $e');
}
} else {
print('Column isshipment does not exist, skipping DROP COLUMN');
}
}
}
Filter Out Non-existent Columns During Data Insertion:
When copying data from the old database to the new one, ensure that you only include the columns that exist in the new table. Modify your copyDataToNewDatabase function as follows:
dart
Future<void> copyDataToNewDatabase(Database _database, Database _newDatabase) async {
// Get the list of columns in the new database's order_history table
var columnData = await _newDatabase.rawQuery('PRAGMA table_info($order_history_table)');
List<String> columns = columnData.map((row) => row['name'] as String).toList();
// Copy data from orderHistoryTable
List<Map<String, dynamic>> orderHistoryData = await _database.query(order_history_table);
for (var newRow in orderHistoryData) {
// Remove any keys not in columns
Map<String, dynamic> filteredRow = {};
newRow.forEach((key, value) {
if (columns.contains(key)) {
filteredRow[key] = value;
}
});
await _newDatabase.insert(order_history_table, filteredRow, conflictAlgorithm: ConflictAlgorithm.replace);
}
// Copy data for the orderHistoryDetailTable similarly
List<Map<String, dynamic>> orderHistoryDetailData = await _database.query(orderhistory_detail_table);
for (var newRow in orderHistoryDetailData) {
await _newDatabase.insert(orderhistory_detail_table, newRow, conflictAlgorithm: ConflictAlgorithm.replace);
}
}
Explanation:
Column Existence Check: By querying PRAGMA table_info(table_name), you get the schema of the table, including all column names. This allows you to verify if a column exists before performing operations on it.
Filtering Data: When inserting data, it's crucial to align the keys in your data maps with the actual columns in the table. By filtering out any keys that don't match, you prevent SQLite from throwing errors about non-existent columns.
Additional Recommendations:
Avoid Using Unsupported SQLite Features: Since ALTER TABLE DROP COLUMN isn't supported in all versions of SQLite, especially older ones, consider alternative methods for schema changes.
Use Migration Scripts: When altering database schemas, it's good practice to use migration scripts that can handle the changes across different versions reliably.
Error Handling: Always wrap database operations in try-catch blocks to gracefully handle any unexpected errors.
Summary:
You're encountering errors because you're trying to manipulate a column (isshipment) that doesn't exist in your order_history table. To fix this:
Before dropping the column, check if it exists.
When inserting data, ensure you're only using columns that actually exist in the table.
By making these changes, you should be able to resolve the errors and have your database operations function as intended.