I am trying to add some data to a table in postgresql through a seed file I've created. all the routes work and I already created another table. However, on this particular table I'm trying to add an array in one of the columns, but I keep getting this error. Does anyone has an idea of what it could be? or how can I inform a postgresql table I want to add some arrays:
```{ scientistSeedError: 'syntax error at or near "["' }````
below is the query to create the table
const query =
CREATE TABLE "scientist" (
"id" serial NOT NULL,
"first_name" varchar(255) NOT NULL,
"last_name" varchar(255) NOT NULL,
"area_expertise" varchar(255) NOT NULL,
"areaExpertise" TEXT ARRAY NOT NULL,
"field" TEXT ARRAY NOT NULL,
"wiki_link" varchar(255) NOT NULL,
"picture" varchar(255) NOT NULL,
"short_description" varchar(400),
CONSTRAINT "scientist_pk" PRIMARY KEY ("id")
) WITH (
OIDS=FALSE
);`
;
try {
await db.query(query);
res.send("Database successfully created");
} catch(e){
console.log(e.message)
}
};```
**and below a fragment of the query to add the data. As is too large to post here but**
```module.exports.seedPart2 = async (req, res, next) => {
// Scientist query
const scientistsQuery = `
INSERT INTO scientist (first_name,
last_name,
area_expertise,
field,
issue_tackled,
wiki_link,
picture) VALUES
('Eugenie', 'Clark', 'Ichthyologist', 'biology', 'Environmental preservation', 'https://en.wikipedia.org/wiki/Eugenie_Clark', 'http://www.alertdiver.com/cdn/13649.jpg'),
('Susan', 'Solomon', 'Atmospheric Chemist', 'Chemistry', ['Environmental preservation', 'Chemistry'], 'https://en.wikipedia.org/wiki/Susan_Solomon' , 'https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/Susan_Solomon-Desk_With_Globe.jpg/1024px-Susan_Solomon-Desk_With_Globe.jpg'),
('Donna Theo', 'Strickland', 'Physics, Optics, and Lasers', 'Physics', ['Medicine', 'New technologies'], 'https://en.wikipedia.org/wiki/Donna_Strickland', 'https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Donna_Strickland_EM1B5760_%2846183560632%29_%28cropped%29.jpg/220px-Donna_Strickland_EM1B5760_%2846183560632%29_%28cropped%29.jpg'),
('Linda', 'Brown Buck', 'Biologist', 'Biology', 'Medicine', 'https://en.wikipedia.org/wiki/Linda_B._Buck', 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Linda_Buck_2015_%28cropped%29.jpg/200px-Linda_Buck_2015_%28cropped%29.jpg')`;
try {
const {rows} = await db.query(scientistsQuery);
res.status(201).json(rows)
} catch (e) {
console.log({ scientistSeedError: e.message });
}
};
Thank you for any help!!!
Array literals in PosgreSQL are denoted by curly braces, not square braces (see the documentation for details):
const scientistsQuery = `
INSERT INTO scientist (first_name,
last_name,
area_expertise,
field,
issue_tackled,
wiki_link,
picture) VALUES
('Eugenie', 'Clark', 'Ichthyologist', 'biology', 'Environmental preservation', 'https://en.wikipedia.org/wiki/Eugenie_Clark', 'http://www.alertdiver.com/cdn/13649.jpg'),
('Susan', 'Solomon', 'Atmospheric Chemist', 'Chemistry', '{"Environmental preservation", "Chemistry"}', 'https://en.wikipedia.org/wiki/Susan_Solomon' , 'https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/Susan_Solomon-Desk_With_Globe.jpg/1024px-Susan_Solomon-Desk_With_Globe.jpg'),
('Donna Theo', 'Strickland', 'Physics, Optics, and Lasers', 'Physics', '{"Medicine", "New technologies"}', 'https://en.wikipedia.org/wiki/Donna_Strickland', 'https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Donna_Strickland_EM1B5760_%2846183560632%29_%28cropped%29.jpg/220px-Donna_Strickland_EM1B5760_%2846183560632%29_%28cropped%29.jpg'),
('Linda', 'Brown Buck', 'Biologist', 'Biology', 'Medicine', 'https://en.wikipedia.org/wiki/Linda_B._Buck', 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Linda_Buck_2015_%28cropped%29.jpg/200px-Linda_Buck_2015_%28cropped%29.jpg')`;
Related
I am making a game and I recently added a server database score saver but I can't figure out how to insert a username only if it doesn't already exist here is the following query:
const addUser = (req, res) => {
const {username, score} = req.body;
pool.query(
'INSERT INTO userlist (username, score) VALUES ($1, $2)',
[username, score],
(err) => {
if(err){
throw err;
}
res.status(201).json({status: "success", message: "User added."});
},
);
}
I am guessing I'll have to change the query
also here is my SQL code for creating the table:
CREATE TABLE userlist(
ID SERIAL PRIMARY KEY,
username VARCHAR(255),
score VARCHAR(255)
);
The best way to handle this is to let the database validate the uniqueness of the username:
alter table userlist add constraint unq_userlist_usename unique(username);
Now if you attempt to insert a single row, then it will return an error if the row already exists.
If you don't want an error you can use an on conflict clause. However, in this case, an exception seems useful to notify the user that username already exists.
use an if statement to identify if the username exist and then update it
if (Users::where('name', $request->user_name)->exists()) {
return response()->json(['record exist']);
} else {
$save = new Users;
$save->name = $request->user_name;
$save->save();
return response()->json(['User saved successfully.']);
}
I am using Testcontainers 1.15.2 (using postgres image 13.2-alpine) with Spring Boot 2.4.3. The Testcontainer is started using an init script which starts with a type definition, a table creation and insert values into it. I even perform a COMMIT; at the end but did not define a schema or so.
When I start the Spring Boot app the console output shows me that the init script was executed successfully.
When I execute a SELECT * FROM the result is empty. So...why are the postgresql tables empty although I did inserts before?
CREATE TYPE Erklaerungstyp AS ENUM ('AAAAA', 'BBBBB', 'CCCCC', 'DDDDD');
CREATE TYPE Geschlecht AS ENUM ('D', 'F', 'M');
DROP TABLE IF EXISTS Anschrift;
CREATE TABLE Anschrift (
a_id SERIAL PRIMARY KEY,
Zusatz VARCHAR(255),
Strasse VARCHAR(30) NOT NULL,
Hausnummer VARCHAR(30) NOT NULL,
plz VARCHAR(5) NOT NULL,
Ort VARCHAR(80) NOT NULL,
Bundesland VARCHAR(20),
Land VARCHAR(20) NOT NULL,
create_Date DATE NOT NULL,
modify_Date DATE
);
INSERT INTO Anschrift VALUES (1, null, 'Musterstrasse', '13M', '12345', 'Berlin', 'Berlin', 'Deutschland', '2001-09-28');
INSERT INTO Anschrift VALUES (2, 'bei Müller', 'Musterweg', '1-3', '54321', 'Musterhausen', 'Muster-Hausen', 'Deutschland', '2002-03-11');
DROP TABLE IF EXISTS Person;
CREATE TABLE Person (
ep_id SERIAL PRIMARY KEY,
Geschlecht Geschlecht,
Vorname VARCHAR(30) NOT NULL,
Familienname VARCHAR(30) NOT NULL,
Geburtsname VARCHAR(30) NOT NULL,
Titel VARCHAR(10),
Geburtsdatum Date NOT NULL,
Geburtsort VARCHAR(30),
Anschrift INTEGER REFERENCES Anschrift(a_id),
Email VARCHAR(80),
Telefon VARCHAR(20),
Versichertennummer VARCHAR(15) NOT NULL,
create_Date DATE NOT NULL,
modify_Date DATE
);
INSERT INTO Person VALUES (1, 'M', 'Max', 'Mustermann', 'Mustermann', 'Dipl.-Inf.', '01.01.1901', 'Berlin', 1, 'Max.Mustermann#max.de',
'0111 12 34 56 789', 'X000Y111Z999', '2001-09-28');
COMMIT;
I instantiate the Testcontainer in an abstract superclass for tests to be used in all inheriting subclassing tests:
#ActiveProfiles("test")
#Testcontainers
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class AbstractApplicationIT {
final static DockerImageName POSTGRES_IMAGE = DockerImageName.parse("postgres:13.2-alpine");
#Container
public static PostgreSQLContainer<?> postgreSQLContainer = new PostgreSQLContainer<>(POSTGRES_IMAGE);
#Test
public void contextLoads() {
}
}
In a subclass I do:
#Transactional
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class XxxIT extends AbstractApplicationIT {
#Value("${spring.datasource.password}")
private String password;
#Value("${spring.datasource.username}")
private String username;
#Value("${spring.datasource.dbname}")
private String dbName;
#Value("${spring.datasource.initScript}")
private String initScript;
#Autowired
private AnschriftJpaDao dao;
#Autowired
private XxxService xxxService;
#BeforeAll
public void setup() {
postgreSQLContainer = new PostgreSQLContainer<>(POSTGRES_IMAGE)
.withDatabaseName(dbName)
.withUsername(username)
.withPassword(password)
.withInitScript(initScript);
postgreSQLContainer.start();
}
#Test
public void checkDbContainerIsAlive() {
assertThat(this.dao.findAll()).isNotNull();
}
}
...and the test is green but when I do
#Test
public void anschrift_can_be_found() {
assertThat(this.dao.findAll().size() == 1);
List<Anschrift> anschriftList = this.dao.findAll();
System.out.println(anschriftList.size());
}
...the test is green but anschriftList is empty. Why?
And if I use Anschriften PK as a FK in Person entity...I get a LazyLoadingException although specifying fetch = FetchType.EAGER in the relationship definitions. Why?
In my application-test.yaml I defined
jpa:
hibernate:
ddl-auto: create-drop
as I found this on the internet.
-> Outcommenting this line leads to filled tables.
I'm trying to do a simple sql insert using nodejs and express trying various formats I've found online, but this appears to be the accepted way. When I view the error it's adding extra backslashes to the query and failing.
The code:
console.log(request.body);
var post = {uid: request.session.uid, title: request.body.title, created: request.body.createdAt};
connection.query('INSERT INTO projects (uid, title, created) SET ? ', post, function (error, results, fields) {
console.log(error);
});
The first body console.log:
{ title: 'aewgawegr', createdAt: '1574219119301' }
The error message:
sqlMessage:
'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'SET `uid` = 1, `title` = \'aewgawegr\', `created` = \'1574219119301\'\' at line 1',
sqlState: '42000',
index: 0,
sql:
'INSERT INTO projects (uid, title, created) SET `uid` = 1, `title` = \'aewgawegr\', `created` = \'1574219119301\' ' }
For reference: https://dev.mysql.com/doc/refman/8.0/en/insert.html
You cannot combine the two usage syntax:
INSERt INTO `table` (column1, ...) VALUES (value1, ...
with
INSERT INTO `table` SET `column1`='value1', ....
You can do something like this instead of passing json object
"INSERT INTO projects (uid, title, created) VALUES (1, 'Michelle', 'Blue Village 1')";
e.g in your case you can use string interpolation:
`INSERT INTO projects (uid, title, created) VALUES ('${request.session.uid}', '${request.body.title}', '${request.body.createdAt}')`;
I've got a table named account_in my PostgreSQL with its fields. You can see it on pic.
When I try to execute script from file it shows me an error that mvccversion fields doesn't exists in account_ table
Here my file with script that I want to run
SET SESSION AUTHORIZATION 'postgres';
SET search_path = public;
--
-- Data for blobs (OID = 28988) (LIMIT 0,1)
--
INSERT INTO account_ ("MVCCVERSION", "ACCOUNTID", "COMPANYID", "USERID", "USERNAME", "CREATEDATE", "MODIFIEDDATE", "PARENTACCOUNTID", "NAME", "LEGALNAME", "LEGALID", "LEGALTYPE", "SICCODE", "TICKERSYMBOL", "INDUSTRY", "TYPE_", "SIZE_") VALUES (11, 208, 206, 0, NULL, '03.04.2017 13:17:53', '02.03.2015 10:31:12', 0, 'TEST', 'TEST', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
COMMIT;
--
What's wrong?
I'm a bit new to code first migrations and it's giving me a headache...
Basically, I'm trying to create a new table of values ('Breeds' in my example). I want to add a column in another table 'Dogs' which holds a BreedId, cannot be null and has a default value.
After a lot of faff, I've ended up with the code below. (It didn't like the adding the foreign key so I had to comment that bit out).
CreateTable(
"dbo.Breeds",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false),
})
.PrimaryKey(t => t.Id);
Sql("SET IDENTITY_INSERT [dbo].[Breeds] ON");
Sql("INSERT into [dbo].[Breeds] ([Id], [Name]) VALUES ('1', 'Long Hair')");
Sql("SET IDENTITY_INSERT [dbo].[Breeds] OFF");
AddColumn("dbo.Dogs", "BreedId", c => c.Int(nullable: false, defaultValue: '1'));
//AddForeignKey("dbo.Dogs", "BreedId", "dbo.Breeds", "Id");
CreateIndex("dbo.Dogs", "BreedId");
But after running Update-Database, the result is:
ALTER TABLE [dbo].[Dogs] ADD [BreedId] [int] NOT NULL DEFAULT 49
CREATE INDEX [IX_BreedId] ON [dbo].[Dogs]([BreedId])
As you can see the default value has become '49' instead of '1'and I have no idea why.
Can anyone see where I'm going wrong, or is there an easier way to achieve what I'm trying to do?
Thanks!
Posting answer thanks to Scotch, removed the quotes then the default value is set correctly.
Like this:
AddColumn("dbo.Dogs", "BreedId", c => c.Int(nullable: false, defaultValue: 1));