ERROR: column "urls" is of type url[] but expression is of type record[] - postgresql

ddl
CREATE TYPE url AS (
url varchar,
status int4);
CREATE TABLE public.tiantang_page (
href varchar NOT NULL,
status int4 NOT NULL,
description varchar NOT NULL,
urls url[] NULL,
urltest url NULL
);
sql
INSERT INTO public.tiantang_page
(href, status, description, urls, urltest)
VALUES('', 0, '', array[row('test',0)], row('test',0));
error
SQL Error [42804]: ERROR: column "urls" is of type url[] but expression is of type record[]
Hint: You will need to rewrite or cast the expression.
Position: 97

As per the error message, you'll need to cast back to your composite url type using ::
INSERT INTO public.tiantang_page
(href, status, description, urls, urltest)
VALUES('', 0, '', array[row('test',0)::url], row('test',0)::url);
SqlFiddle

Related

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),
];

Postgresql - querying jsonb throws a syntax error

I have a table that has a column data of jsonb type.
create table event
(
id bigserial
primary key,
created_at timestamp with time zone default now() not null,
type text not null,
created_by text,
data jsonb,
event_time timestamp with time zone default now() not null
);
In that field I am saving a json object that looks like this:
{
"comment": "Changed by recipient",
"source": "Recipient page"
}
I would like to query values in that table by the value of the comment property of the data json object. Something like this in based by examples [here][1]:
select * from event
where type = 'pickup-data-changed'
and data -> 'comment' = 'Changed by recipient'
If I query like that I get an invalid token error:
[22P02] ERROR: invalid input syntax for type json Detail: Token "Changed" is invalid. Position: 104
What am I doing wrong here?
If I do it as a double arrow like suggested in the comments:
select * from event
where type = 'pickup-data-changed'
and data ->-> 'comment' = 'Changed by recipient'
I get an error:
[42883] ERROR: operator does not exist: jsonb ->-> unknown Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
How can I make this query work?
[1]: https://kb.objectrocket.com/postgresql/how-to-query-a-postgres-jsonb-column-1433
I get an invalid token error. What am I doing wrong here?
data -> 'comment' returns a value of type jsonb, so the right hand side of the comparison 'Changed by recipient' is parsed as JSON as well - and it's invalid JSON. To create a JSON string value to compare against, you'd need to write
… data -> 'comment' = '"Changed by recipient"'
If I do it as a double arrow like suggested in the comments, data ->-> 'comment'
The comments suggested
… data ->> 'comment' = 'Changed by recipient'
not ->->.
alternatives:
select * from event
where type = 'pickup-data-changed'
and data -> 'comment' = '"Changed by recipient"'::jsonb;
or
select * from event
where type = 'pickup-data-changed'
and data['comment'] = '"Changed by recipient"'::jsonb;

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)

sql: Scan error on column index 1, name "u.duration": converting driver.Value type []uint8 ("MORE") to a int: invalid syntax

I have enum filed in the table. When I do a SELECT query with the help of Select() method, I get:
sql: Scan error on column index 1, name "u.duration": converting driver.Value type []uint8 ("MORE") to a int: invalid syntax
my DB structure
CREATE TYPE duration_type AS ENUM ('TWO_MONTHS', 'SIX_MONTHS', 'ONE_YEAR','MORE');
CREATE TABLE shake_hands
(
id uuid,
duration duration_type NOT NULL,
phone_number TEXT,
email_address TEXT,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
my structs
type DurationType int
type ShakesHands struct {
ID uuid.UUID `db:"id"`
PhoneNumber string `db:"phone_number"`
Duration DurationType
Email *string `db:"email_address"`
ModelIds []string
}
Anything else need to be pasted here?

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.