Can't store user_id into another table in flutter - 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),
];

Related

postgresql transactions violates foreign key constraint

I have the following nodejs code (simplified):
// tables
CREATE TABLE admins (
admin_id bigint DEFAULT nextval('admins_seq') NOT NULL,
username character varying(25) NOT NULL,
password character varying(150) NOT NULL
);
CREATE TABLE admin_notifications (
admin_notification_id bigint DEFAULT nextval('admin_notifications_seq') NOT NULL,
admin_id bigint NOT NULL,
type character varying(150) NOT NULL
);
ALTER TABLE admin_notifications ADD CONSTRAINT admin_notifications_to_admins_fk FOREIGN KEY (admin_id) REFERENCES admins(admin_id) ON DELETE CASCADE;
await client.query('BEGIN');
// create a new array in the database and return the newly created admin id
const query = 'INSERT INTO admins (username, password) VALUES($1,$2) RETURNING admin_id';
const values = [];
const result = await client.query(query, values);
// insert a welcome notification for the newly created admin
const query2 = 'INSERT INTO admin_notifications (admin_id, type) VALUES ($1,$2)';
const values2 = [result.rows[0].admin_id, 'welcome'];
const result2 = await client.query(query2, values2);
await client.query('COMMIT');
A little explanation: i create a new admin in the table admins. When a new admin is created, I want to insert a new welcome notification in the table admin_notifications. The column admin_id in the table admin_notifications is a foreign key to the table admins (admin_id).
I get the following error:
Error: insert or update on table "admin_notifications" violates foreign key constraint "admin_notifications_to_admins_fk"
When I leave out the transactions it works?!
Does it has something to do with deferring constraints? And how to handle this in my code?

How can I return a column value in postgresql when inserting into the table?

I have a table of in the format
userid uuid DEFAULT uuid_generate_v4 (),
username VARCHAR NOT NULL,
email VARCHAR NOT NULL,
password VARCHAR NOT NULL,
password_salt VARCHAR NOT NULL,
creation_date timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP
When I insert into the table, I a uuid is generated. How can I retrieve the uuid generated from an insert command without sending another select query? The best I have is something like this:
INSERT into user (username, email, password, salt) VALUES ('user', 'email', 'password', 'salt')
RETURNING uuid;
but it doesn't work because it doesn't know what the uuid variable I am referring to.
You return the column name not a data type:
insert into user (username, email, password, salt)
values ('user', 'email', 'password', 'salt')
returning userid;

What is Causing this Dart Sq3Lite Database Exception Error?

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

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.