Cannot create stored procedure to insert data: type mismatch for serial column - sql

CREATE TABLE test ( id serial primary key, name text );
CREATE OR REPLACE PROCEDURE test_insert_data( "name" text)
LANGUAGE SQL
AS $$
INSERT INTO public.test values("name")
$$;
Error & Hint:
column "id" is of type integer but expression is of type character varying
LINE 4: INSERT INTO public.test values("name")
^
HINT: You will need to rewrite or cast the expression.
I followed this tutorial: https://www.enterprisedb.com/postgres-tutorials/10-examples-postgresql-stored-procedures.
Obviously, I don't need to attach the column id for inserting.

There is no quoting issue, like comments would suggest.
And the linked tutorial is not incorrect. (But still bad advise.)
The missing target column list is the problem.
This would work:
CREATE OR REPLACE PROCEDURE test_insert_data("name" text)
LANGUAGE sql AS
$proc$
INSERT INTO public.test(name) -- !! target column list !!
VALUES ("name");
$proc$;
(For the record, since "name" is a valid identifier, all double quotes are just noise and can (should) be omitted.)
If you don't specify the target column(s), Postgres starts to fill in columns from left to right, starting with id in your case - which triggers the reported error message.
(The linked tutorial also provides an ID value, so it does not raise the same exception.)
Even if it would work without explicit target column list, it's typically still advisable to add one for persisted INSERT commands. Else, later modifications to the table structure can break your code silently. With any bad luck in a way you'll only notice much later - like filling in the wrong columns without raising an error.
See:
SQL INSERT without specifying columns. What happens?
Inserting into Postgres within a trigger function
Aside: I would never use "name" as column name. Not even in a generic tutorial. That's not helpful. Any column name is a "name". Use meaningful identifiers instead.

Related

Error: ORA-04043: object table name does not exist when describing any table within a specific user workstation from the SQL command line

I have created tables in Oracle DB from the SQL command line, and I'm having a problem when describing the table, when going through the oracle application express web page I can see them there.
The oracle version I have is the following:
SQL*Plus: Release 11.2.0.2.0 Production
The following is the command I used to create a table in the database:
CREATE TABLE "Product"
( "ProuctID" VARCHAR2(8) NOT NULL ENABLE,
"ProductExpiryDate" DATE,
"CustomerID" VARCHAR2(8),
CONSTRAINT "Product_PK" PRIMARY KEY ("ProductID") ENABLE
) ;
Command for describing the table:
Desc Product;
But at the end after creating each table and describe it I get this:
ORA-04043: object Product does not exist
Can anyone please tell me why I am I getting this, when I can see it in Oracle Xpress web page?
By enclosing the table name in double quotes, you created the table with a case-sensitive name. To correctly specify the name, you now have to always enclose it in double quotes.
So instead of Desc Product, you need Desc "Product".
Because this is quite cumbersome and error-prone, it's usually best to avoid enclosing table and column names in double quotes in the first place. If possible, I'd recommend you either drop & recreate the table or rename it.

How can I alter a UDT in HSQLDB?

In HSLQDB v 2.3.1 there is a create type clause for defining UDTs. But there appears to be no alter type clause, as far as the docs are concerned (and the db returns a unexpected token error if I try this).
Is it possible to amend/drop a UDT in HSQLDB? What would be the best practice, if for example I originally created
create type CURRENCY_ID as char(3)
because I decide I'm going to use ISO codes. But then I actually decide that I'm going to store the codes as integers instead. What is the best way to modify the schema in my db? (this is a synthetic example, obviously I wouldn't use integers in this case).
I guess I might do
alter table inventory alter column ccy set data type int
drop type CURRENCY_ID
create type CURRENCY_ID as int
alter table inventory alter column ccy set data type CURRENCY_ID
but is there a better way to do this?
After trying various methods, I ended up writing a script to edit the *.script file of the database directly. It's a plain text file with SQL commands that recreates the DB programmatically. In detail:
open db, shutdown compact
Edit the script file: replace the type definition, e.g. create type XXX as int to create type XXX as char(4)
For each table, replace the insert into table XXX values (i,...) with insert into table XXX values('str',...). This was done with a script that had the mappings from the old (int) value into the new (char) value.
In my particular case, I was changing a primary key, so I had to remove the identity directive from the create table statement, and also I had to remove a line that had a alter table XXX alter column YYY restart sequence 123.
save and close script file, open db, shutdown compact
This isn't great, but it worked. Advantages :
Ability to re-define UDT.
Ability to map the table values programmatically.
Method is generic and can be used for other schema changes, beside UDTs.
Cons
No checking that schema is consistent (although it does throw up errors if it can't read the script).
Dangerous when reading file as a text file. e.g. what if I have a VARCHAR column with newlines in it? When I parse the script file and write it back, this would need to be escaped.
Not sure if this works with non-memory DBs. i.e. those that don't only have a *.script file when shutdown.
Probably not efficient for large DBs. My DB was small ~ 1MB.

HSQLDB user lacks privilege or object not found error when making select statements with where

I use SQuirrel SQL Client Version 3.5.3 and HSQLDB for my database. I have been able to specify the corresponding driver (In-memory) to it and create an Alias.
I have created a table
CREATE TABLE ENTRY(
NAME VARCHAR(100) NOT NULL,
DESC VARCHAR(500) NOT NULL,
PRIMARY KEY (NAME))
and added a few lines of data into it. While statements like these work:
select * from ENTRY
select NAME from ENTRY
select DESC from ENTRY
I always get Error: user lacks privilege or object not found"
when adding a where clause to my statement, e.g. select DESC from ENTRY where NAME=CAR
Any help is greatly appreciated as I can slowly feel my sanity waning
I had the same problem, but my table name and other things were ok except my query for VARCHAR were inside double quotes("") but it should be in single quotes('')
example:
assume you have table like this which flightId is primary key
now this query is wrong:
SELECT * FROM flights WHERE flightId="0f3ae9b3-6bb1-4c95-9394-6179555f5879"
while this one is ok:
SELECT * FROM flights WHERE flightId='0f3ae9b3-6bb1-4c95-9394-6179555f5879'
I was finally able to fix this myself. I had used a wrong table name for my select statements and after changing it to the real one it worked. The only thing that confuses me is that I also used the wrong table name for my insert statements but they were executed successfully and all data is showing up in them.
HSQLDB has default schema called PUBLIC. All SQL queries will be pointing to PUBLIC; If you have created your own schema like eg:OWNSCHEMA then edit the xxx.script and change the following line
SET DATABASE DEFAULT INITIAL SCHEMA PUBLIC
to
SET DATABASE DEFAULT INITIAL SCHEMA OWNSCHEMA
When I received the same exception the root cause was that I had a table in the SELECT clause that was not present in the FROM clause.
Your problem is:
I always get Error: user lacks privilege or object not found" when
adding a where clause to my statement, e.g. select DESC from ENTRY
where NAME=CAR
Yes, of course you do.
NAME is a field of the ENTRY table. CAR isn't a field of anything.
Perhaps your WHERE clause should look like this instead:
WHERE NAME='CAR'
Thereby comparing a field value with a literal string value instead of trying to compare it with a nonexistent other field value.

What is the use of $$ sign in table name in Oracle Database

I get to maintain a application which use $$ sign as prefix and suffix to some word in the table create statement - Oracle DB. like
create table $$temp$$(id int)
For testing purpose I ran the statement in SQL plus but it threw invalid character error and so I had to remove $$ sign and then it ran as expected.
Is there a specific use for $$? some thing related to session ?
Is there a specific use for $$
No there is not. Dynamic performance views, however, have one dollar sign ($) in their names, v$sql, for example. It's Oracle's choice to name them that way.
You won't be able create a table, which name starts with dollar sign($), simply because any non-quoted identifier should begin with an alphabetic character. You can however force Oracle to accept an identifier that begins with a non-alphabetic character if you enclose it with double quotation marks, like so
create table "$$temp$$"(
id int
)
but it should be noted that when you created a table using double quotation marks, you made that table name case-sensitive (unless you didn't type the table name in uppercase) and would always have to use double quotation marks when referencing that table.
You can create, and later drop, the table with nonstandard characters by using double(!) quotes around the table name: create table "$$tmp$$"(id int). And no, the $ doesn't have any special meaning, except that it shouldn't be used by the user, because various internal tables have names that contain a $ (think v$session). The $ is supposed to avoid name conflicts.

Oracle why does creating trigger fail when there is a field called timestamp?

I've just wasted the past two hours of my life trying to create a table with an auto incrementing primary key bases on this tutorial, The tutorial is great the issue I've been encountering is that the Create Target fails if I have a column which is a timestamp and a table that is called timestamp in the same table...
Why doesn't oracle flag this as being an issue when I create the table?
Here is the Sequence of commands I enter:
Creating the Table:
CREATE TABLE myTable
(id NUMBER PRIMARY KEY,
field1 TIMESTAMP(6),
timeStamp NUMBER,
);
Creating the Sequence:
CREATE SEQUENCE test_sequence
START WITH 1
INCREMENT BY 1;
Creating the trigger:
CREATE OR REPLACE TRIGGER test_trigger
BEFORE INSERT
ON myTable
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT test_sequence.nextval INTO :NEW.ID FROM dual;
END;
/
Here is the error message I get:
ORA-06552: PL/SQL: Compilation unit analysis terminated
ORA-06553: PLS-320: the declaration of the type of this expression is incomplete or malformed
Any combination that does not have the two lines with a the word "timestamp" in them works fine. I would have thought the syntax would be enough to differentiate between the keyword and a column name.
As I've said I don't understand why the table is created fine but oracle falls over when I try to create the trigger...
CLARIFICATION
I know that the issue is that there is a column called timestamp which may or may not be a keyword. MY issue is why it barfed when I tried to create a trigger and not when I created the table, I would have at least expected a warning.
That said having used Oracle for a few hours, it seems a lot less verbose in it's error reporting, Maybe just because I'm using the express version though.
If this is a bug in Oracle how would one who doesn't have a support contract go about reporting it? I'm just playing around with the express version because I have to migrate some code from MySQL to Oracle.
There is a note on metalink about this (227615.1) extract below:
# symptom: Creating Trigger fails
# symptom: Compiling a procedure fails
# symptom: ORA-06552: PL/SQL: %s
# symptom: ORA-06553: PLS-%s: %s
# symptom: PLS-320: the declaration of the type of this expression is incomplete or malformed
# cause: One of the tables being references was created with a column name that is one of the datatypes (reserved key word). Even though the field is not referenced in the PL/SQL SQL statements, this error will still be produced.
fix:
Workaround:
1. Rename the column to a non-reserved word.
2. Create a view and alias the column to a different name.
TIMESTAMP is not listed in the Oracle docs as a reserved word (which is surprising).
It is listed in the V$RESERVED_WORDS data dictionary view, but its RESERVED flag is set to 'N'.
It might be a bug in the trigger processing. I would say this is a good one for Oracle support.
You've hinted at the answer yourself. You're using timestamp as a column name but it's also a keyword. Change the column name to something else (eg xtimestamp) and the trigger compiles.
Well, I'm not totally sure about it, but I think this happens because the SQL code used to manipulate and access database objects is interpreted by some interpreter different form the one used to interpret PL/SQL code.
Have in mind that SQL an PL/SQL are different things, and so they are processed differently. So, I think there is some error in one interpreter, just not sure which one is.
Instead of having Oracle maintain a view, use EXECUTE IMMEDIATE (i.e. if 'Rename the column to a non-reserved word' is not an option.
You can execute via EXECUTE IMMEDIATE. IT's not better way but work's and avoid column rename.
In my case rename column will be a caotic way