What is Causing this Dart Sq3Lite Database Exception Error? - flutter

Thank you in advance for your help.
This issue has been driving me crazy for the past couple of days. I have searched every site that Google has returned and still the resolutions haven't helped.
I am attempting to create a Sq3Lite database using Dart and keeping getting a DatabaseException error when trying to create a table that uses foreign keys. I've tried turning foreign key use on with 'PRAGMA foreign_keys = ON' as well but no luck. I am also using an IOS simulator in Android Studio and delete the app before running the code with attempted fixes.
Here is my code:
final int version = 1;
Database db;
Future<Database> openDb() async {
if (db == null) {
db = await openDatabase(join(await getDatabasesPath(), 'skeema.db'), onCreate: (database, version) {
database.execute('CREATE TABLE Account(id INTEGER PRIMARY KEY, Name TEXT NOT NULL, CurrencyType TEXT NOT NULL, ' + 'Balance REAL NOT NULL, IsPrimary TEXT NULL)');
database.execute('CREATE TABLE BudgetItem(id INTEGER PRIMARY KEY, Name TEXT NOT NULL, Icon TEXT NOT NULL, Budget REAL NOT NULL, ' + 'IsPrimary TEXT NULL)');
database.execute('CREATE TABLE TransactionType(id INTEGER PRIMARY KEY, Type TEXT NOT NULL)');
database.execute('CREATE TABLE Transaction(id INTEGER PRIMARY KEY, Account_id INTEGER NOT NULL, BudgetItem_id INTEGER NOT NULL, ' +
'TransactionType_id INTEGER NOT NULL, Amount REAL NOT NULL, Date TEXT NOT NULL, Party TEXT NOT NULL, Note TEXT NULL, ' +
'FOREIGN KEY(Account_id) REFERENCES Account(id), ' +
'FOREIGN KEY(BudgetItem_id) REFERENCES BudgetItem(id), ' +
'FOREIGN KEY(TransactionType_id) REFERENCES TransactionType(id))');
}, version: version);
}
return db;
}
Here is the error:
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: DatabaseException(Error Domain=FMDatabase Code=1 "near "Transaction": syntax error" UserInfo={NSLocalizedDescription=near "Transaction": syntax error}) sql 'CREATE TABLE Transaction(id INTEGER PRIMARY KEY, Account_id INTEGER NOT NULL, BudgetItem_id INTEGER NOT NULL, TransactionType_id INTEGER NOT NULL, Amount REAL NOT NULL, Date TEXT NOT NULL, Party TEXT NOT NULL, Note TEXT NULL, FOREIGN KEY(Account_id) REFERENCES Account(id), FOREIGN KEY(BudgetItem_id) REFERENCES BudgetItem(id), FOREIGN KEY(TransactionType_id) REFERENCES TransactionType(id))' args []}
#0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7)
<asynchronous suspension>
#1 SqfliteDatabaseFactoryImpl.wrapDatabaseException (package:sqflite/src/factory_impl.dart:27:7)
#2 SqfliteDatabaseMixin.safeInvokeMethod (package:sqflite_common/src/database_mixin.dart:208:15)
#3 SqfliteDatabaseMixin.invokeExecute (package:sqflite_common/src/database_mixin.dart:370<…>
The first 3 tables get created successfully every time but the last table throws the error. Any help is greatly appreciated.
Thank you.

Transaction is a Sq3Lite keyword, so you can't name your table that. So give it any other name and it will work.
There may be ways to use that name anyway if you escape it, but the easy solution is just to choose a different name.
List of all keywords: https://www.sqlite.org/lang_keywords.html

Related

Problem with SQL workbench crash on MacOS

I'm trying to make MySQL work on my MacBook (intel CPU). I have downloaded the Server and I'm using the workbench to write the SQL. But whenever I try to make a database the workbench crashes and gives me the error:
Termination Reason: Namespace SIGNAL, Code 4 Illegal instruction: 4
Terminating Process: exc handler [933]
I have not changed any settings, it's all factory settings.
CREATE DATABASE Fisk;
USE Fisk;
create table fisk (
fisk_id int not null,
navn char(25) not null,
max_laengde_cm int not null,
primary key (fisk_id)
);
create table plads (
plads_id int not null,
navn char(25) not null,
afstand_fra_hjem_km int not null,
primary key(plads_id)
);
create table redskab(
redskab_id int not null,
navn char(25) not null,
vaegt_gram int not null,
primary key (redskab_id)
);
create table fisketur(
fisketur_id int not null,
dato date not null,
plads_id int not null,
primary key (fisketur_id),
foreign key (plads_id) references plads(plads_id)
);
create table fangst(
fangst_id int not null,
tid time not null,
laengde_cm int not null,
fisk_id int not null,
fisketur_id int not null,
redskab_id int not null,
primary key (fangst_id),
foreign key (fisk_id) references fisk(fisk_id),
foreign key (fisketur_id) references fisketur(fisketur_id),
foreign key (redskab_id) references redskab(redskab_id)
);
insert into fisk values
(1,'Hornfisk',90),
(2,'Torsk',120),
(3,'Skrubbe',50),
(4,'Makrel',45),
(5,'Laks',120);
insert into plads values
(1,'Knudshoved',31),
(2,'Vresen',45),
(3,'Fyns Hoved',48),
(4,'Gabet',24),
(5,'Kajbjerg',34);
insert into redskab values
(1,'R¯dt blink',25),
(2,'Gr¯n flue',5),
(3,'Forfang',55),
(4,'Blankt blink',35),
(5,'Gult blink',28);
insert into fisketur values
(1,'2018-10-18',4),
(2,'2019-11-23',2),
(3,'2019-06-12',3),
(4,'2019-12-11',1),
(5,'2020-01-02',1),
(6,'2014-10-14',5);
insert into fangst values
(1,'12:17:00',48,4,5,1),
(2,'15:38:00',35,3,4,3),
(3,'19:30:00',50,2,3,5),
(4,'09:28:00',41,1,2,4),
(5,'07:12:00',43,5,1,2),
(6,'05:48:00',55,1,3,2),
(7,'09:56:00',62,2,6,4);
SHOW TABLES;

Can't store user_id into another table in flutter

I need to create a table that will add the user_id as another data in the table. But somehow my solution does not work.
The table user looks like this:
CREATE TABLE user(
user_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
username TEXT NOT NULL,
password TEXT NOT NULL,
f_name TEXT NOT NULL,
l_name TEXT NOT NULL,
email TEXT NOT NULL,
phone INTEGER NOT NULL
)
After the login, the user have to fill in a form, the data goes to the table, flowerbook:
CREATE TABLE flowerbook(
book_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
deliver_date TEXT NOT NULL,
arrangement TEXT NOT NULL,
flower_type TEXT NOT NULL,
user_id INTEGER NOT NULL
)
I tried doing this, on the submit button of the form:
onPressed: () {
Flowerbook flowerbook = Flowerbook(
deliver_date: dateController.text,
flower_type: checkboxController.text,
arrangement: dropdownController.text,
user_id: widget.user.user_id,
);
Flowerbook.register(flowerbook);
},
But I still get this error:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(NOT NULL constraint failed: flowerbook.user_id (code 1299 SQLITE_CONSTRAINT_NOTNULL)) sql 'INSERT OR REPLACE INTO flowerbook (book_id, deliver_date, arrangement, flower_type, user_id) VALUES (NULL, ?, ?, ?, NULL)' args [1/1/2023 12:00:00, Box, Carnation]
As you can see, the delivery_date, flower_type, and arrangement is successfully added as an argument. But user_id is NULL.
What seems to be the problem here?
I did log the widget.user.user_id, and it is indeed NULL.
Maybe there's something wrong at my menu page? Here's my code:
final List<Widget> _widgetOptions = <Widget>[
FormPage(user: widget.user),
OrderPage(user: widget.user),
AccountPage(user: widget.user),
];

MIGRATION FAILED ENUM TYPE ALREADY EXISTS ERROR

I'm building a microservices app using Spring Boot + Postgres + Flyway,
within flight-archive microservice, I created a script sql that contains the following code:
CREATE TYPE Payment_method AS ENUM ('CASH', 'PAYPAL', 'CREDIT CARD');
CREATE TABLE IF NOT EXISTS flight_booking_archive (
booking_Id INT NOT NULL PRIMARY KEY,
flight_Id INT NOT NULL,
passenger_Id INT NOT NULL,
adults INT NOT NULL,
babies INT NOT NULL,
amount_paid MONEY,
payment_method Payment_method,
booked DATE DEFAULT CURRENT_DATE,
CONSTRAINT fk_flight_id FOREIGN KEY (flight_Id) references flight(flight_ID),
CONSTRAINT fk_passenger_id FOREIGN KEY (passenger_Id) references passenger(passenger_ID)
)
then, when I run flight-archive microservice using maven, I got the following error
SQL State : 42710
Error Code : 0
Message : ERROR: type "payment_method" already exists
Location : db/migration/V1__flight_archive_table.sql (C:\Users\OMAYMA\flight-app-
demo\server\flight-booking-
archive\target\classes\db\migration\V1__flight_archive_table.sql)
Line : 1
Statement : CREATE TYPE Payment_method AS ENUM ('CASH', 'PAYPAL', 'CREDIT CARD')
In Postgres if you want to use uppercase you have to use quotation marks, otherwise, the words will always be in lowercase.
Try making this change:
CREATE TYPE "Payment_method" AS ENUM ('CASH', 'PAYPAL', 'CREDIT CARD');
CREATE TABLE IF NOT EXISTS flight_booking_archive (
booking_Id INT NOT NULL PRIMARY KEY,
flight_Id INT NOT NULL,
passenger_Id INT NOT NULL,
adults INT NOT NULL,
babies INT NOT NULL,
amount_paid MONEY,
payment_method "Payment_method",
booked DATE DEFAULT CURRENT_DATE,
CONSTRAINT fk_flight_id FOREIGN KEY (flight_Id) references flight(flight_ID),
CONSTRAINT fk_passenger_id FOREIGN KEY (passenger_Id) references passenger(passenger_ID)

Error saving row in Postgres and how to fix it?

In my Laravel 5.6/PostgreSQL 10.5 application
I want to save data in table :
CREATE TABLE public.rt_orders (
id serial NOT NULL,
user_id int4 NULL,
card_owner varchar(100) NOT NULL,
discount int4 NULL DEFAULT 0,
discount_code varchar(255) NULL,
qty_count int4 NOT NULL,
price_total int4 NOT NULL,
payment varchar(255) NOT NULL,
completed bool NOT NULL DEFAULT false,
error_message varchar(255) NULL,
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT rt_orders_pkey PRIMARY KEY (id),
CONSTRAINT orders_user_id_foreign FOREIGN KEY (user_id) REFERENCES rt_users(id) ON UPDATE CASCADE ON DELETE SET NULL
)
with code :
try {
DB::beginTransaction();
$insertOrderData= [
'user_id'=> $loggedUser->id,
'card_owner'=> $card_owner,
'qty_count'=> Cart::instance('default')->count(),
'price_total'=> Cart::instance('default')->subtotal(),
'payment'=> 'stripe',
'completed'=> true
];
$newOrder = Order::create($insertOrderData);
and I got error:
SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: "3500.75" (SQL: insert into "rt_orders" ("user_id", "card_owner", "qty_count", "price_total", "payment", "completed") values (5, gdfgdfgds, 2, 3500.75, stripe, 1) returning "id") {"userId":5,"email":"admin#mail.com","exception":"[object] (Illuminate\\Database\\QueryException(code: 22P02): SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: \"3500.75\" (SQL: insert into \"rt_orders\" (\"user_id\", \"card_owner\", \"qty_count\", \"price_total\", \"payment\", \"completed\") values (5, gdfgdfgds, 2, 3500.75, stripe, 1) returning \"id\") at /mnt/_work_sdb8/wwwroot/lar/ArtistsRating/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, PDOException(code: 22P02): SQLSTATE[22P02]: I
Why error ?
I tried to copy the sql statement in my sql editor and payed attention that a statement like :
insert into "rt_orders" ("user_id", "card_owner", "qty_count", "price_total", "payment", "completed") values (5, fsdf, 2, 3500.75, stripe, 1)
1) Values entered as string values are without ‘’
2) and got error as last parameter was integer value not boolean:
SQL Error [42804]: ERROR: column "completed" is of type boolean but expression is of type integer
Hint: You will need to rewrite or cast the expression.
Position: 149
I tried in my model to add method:
<?php
namespace App;
use DB;
use App\MyAppModel;
use App\User;
use App\SongOrder;
class Order extends MyAppModel
{
protected $table = 'orders';
protected $primaryKey = 'id';
public $timestamps = false;
protected static function boot() {
parent::boot();
}
protected $fillable = ['user_id', 'card_owner', 'discount', 'discount_code', 'price_total', 'qty_count', 'price_total', 'payment', 'completed', 'error_message'];
public function getCompletedAttribute($value)
{
$this->debToFile(print_r($value,true),' 000 getCompletedAttribute -7 $value::');
$ret= (int)$value == 1;
$this->debToFile(print_r($ret,true),' 000 getCompletedAttribute -7 $ret::');
return $ret;
}
debToFile - is my debugging method and looks like the getCompletedAttribute is not triggered as I do not see my debigiing info of this method.
Can somebody give a hint why this error and how to fix it?
Thanks!
Your price_total has a data type is wrong
price_total int4 NOT NULL,
should be
price_total numeric(10,2) NOT NULL,
where 10 is the max total digits, and 2 is the number of digits after the decimal.
You can also use the money data type (not recommended)
price_total money NOT NULL,
Whatever you do, do NOT use any type of float.

PostgreSQL foreign key create error

I'm new to PostgreSQL and trying to create table with foreign keys.But I got error below.
create table User_Role
(
RoleId serial primary key not null,
RoleCode varchar(21),
Rolename varchar(30),
isActive bool
)
CREATE TABLE User_Account(
UserId serial primary key not null,
RoleId_ref int REFERENCES User_Role (RoleId) NULL,
Username text NULL,
Password text NULL,
IsActive bool NULL
)
CREATE TABLE User_Profile(
ProfileId serial primary key not null,
UserId_ref int REFERENCES User_Account (UserId) NULL,
RoleId_ref int REFERENCES User_Role (RoleId) NULL,
FirstName Text NULL,
LastName Text NULL,
Address Text NULL,
City varchar(100) NULL
)
first two table created successfully. But last table occur create error.
ERROR: column "roleid" referenced in foreign key constraint does not exist
SQL state: 42703
but I can't understand why.