Cause: org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend - postgresql

I am using mybatis to insert the data into postgresql db. I have 19629 number of records to insert. I am trying to insert all records in one time. But if I pass more that 6k records to the query I am getting Cause: org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
So is there any limit to number of insert records in one time in postgresql?
Mybatis code.
{ #Insert({ "<script>","insert into temp_overdrive_csv_dtls (lpat_library_card_number,day_of_use,sessions,minutes_read,hours_read,sys_created_by)","values ", "<foreach collection='recordList' item='record' separator=','>","(#{record.lpatLibraryCardNumber},#{record.dayofUse}, #{record.sessions}, #{record.minutesRead}, #{record.hoursRead}, #{record.sysCreatedBy})","</foreach>", "</script>" })public Integer insert(#Param("recordList") List<CsvRecord> recordList);
Error.
Error updating database. Cause: org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
The error may involve com.apds.mybatis.mapper.overdrive.OverdriveTotMapper.insert-Inline
The error occurred while setting parameters
SQL: insert into temp_overdrive_csv_dtls (lpat_library_card_number,day_of_use,sessions,minutes_read,hours_read,sys_created_by) values (?,?, ?, ?, ?, ?) , (?,?, ?, ?, ?, ?) , (?,?, ?, ?, ?, ?) , (?,?, ?, ?, ?, ?) , , (?,?, ?, ?, ?, ?)
Cause: org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:23)
at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:150)
at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:137)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:46)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:43)
at com.sun.proxy.$Proxy79.insert(Unknown Source)
at com.apds.overdrive.service.OverdriveService.processRequest(OverdriveService.java:105)
at com.apds.overdrive.PartnerOverdriveApplication.main(PartnerOverdriveApplication.java:75)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)Caused by: org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:336)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:446)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:370)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:149)
at org.postgresql.jdbc.PgPreparedStatement.execute(PgPreparedStatement.java:138)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:41)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:66)
at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:45)
at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:100)
at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:75)
at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:148)
... 11 more
#
Caused by: java.io.IOException: Tried to send an out-of-range integer as a 2-byte value: 36000
at org.postgresql.core.PGStream.sendInteger2(PGStream.java:252)
at org.postgresql.core.v3.QueryExecutorImpl.sendParse(QueryExecutorImpl.java:1470)
at org.postgresql.core.v3.QueryExecutorImpl.sendOneQuery(QueryExecutorImpl.java:1793)
at org.postgresql.core.v3.QueryExecutorImpl.sendQuery(QueryExecutorImpl.java:1356)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:301)
... 21 more

It is not the number of rows, but the number of placeholders.
Most drivers have a limit on the number of placeholders of PreparedStatement (32767 with pgjdbc, I think).
This is one of the reasons why multi-row insert is not recommended when inserting or updating a large number of rows (another reason is performance).
You should switch to batch insert.
Please see this answer for an example code.

Related

Issue in importing dashboard in superset

I facing the issue while trying to export dashboard from server to another server of same version 1.5, but showing error: Integrity error. How to import dashboard?
ERROR: (while importing Dashboard)
sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.IntegrityError) UNIQUE constraint failed: tables.table_name
[SQL: INSERT INTO tables (uuid, created_on, changed_on, description, default_endpoint, is_featured, filter_select_enabled, "offset", cache_timeout, params, perm, schema_perm, is_managed_externally, external_url, table_name, main_dttm_col, database_id, fetch_values_predicate, schema, sql, is_sqllab_view, template_params, extra, created_by_fk, changed_by_fk) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]
[parameters: (<memory at 0x7f3b7c882640>, '2022-11-18 11:22:47.890965', '2022-11-18 11:22:47.890971', None, None, 0, 0, 0, None, '{"remote_id": 19, "database_name": "PostgreSQL", "import_time": 1668750767}', None, None, 0, None, 'storefrequency', None, '7', None, None, None, 0, None, None, 1, 1)]
(Background on this error at: http://sqlalche.me/e/13/gkpj) (Background on this error at: http://sqlalche.me/e/13/7s2a)
2022-11-18 11:22:47,893:INFO:werkzeug:127.0.0.1 - - [18/Nov/2022 11:22:47] "POST /superset/import_
I also changed the VERSIONED_EXPORT=True and DASHBOARD_RBAC=True but still it showing a error.

having syntax error trying to use on duplicate

sql_insert_query = "insert into TABLE1 (building, course, description, course_type, course_type_desc, dual_credit)
VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE building = VALUES(building), course = VALUES(course), description = VALUES(description), course_type = VALUES(course_type), course_type_desc = VALUES(course_type_desc), dual_credit = VALUES(dual_credit);"
cursor.executemany(sql_insert_query, listCourse)
pyodbc.ProgrammingError: ('42000', u"[42000] [Microsoft][SQL Server
Native Client 11.0][SQL Server]Incorrect syntax near the keyword 'ON'.
(156) (SQLExecDirectW); [42000] [Microsoft][SQL Server Native Client
11.0][SQL Server]Statement(s) could not be prepared. (8180)")
This one below only works, but adds duplicate when running again.
"insert into TABLE1 (building, course, description, course_type, course_type_desc, dual_credit) VALUES (?, ?, ?, ?, ?, ?)"
I tied '%s' this did not work so I am using '?'
I have resolved it by tile with tuple
listCourse = numpy.tile(courses, 2)
listCourse = map(tuple,numpy.tile(courses, 2))

Collation over DDEV TYPO3 instance

I got a TYPO3 8.7 instance running over a server whose database and tables collation is utf8mb4_unicode_ci. The character set is utf8mb4.
However, MySQL over the server shows the collation for the connection is latin1_swedish_ci and collation for the server is utf8_general_ci (I guess these are parameters that come pre-configured with the hosting):
+----------------------+--------------------+
| Variable_name | Value |
+----------------------+--------------------+
| collation_connection | latin1_swedish_ci |
| collation_database | utf8mb4_unicode_ci |
| collation_server | utf8_general_ci |
+----------------------+--------------------+
3 rows in set (0.00 sec)
I would like to reproduce all these settings over my DDEV instance. I got the last two variable names properly configured with these settings over my .ddev/mysql/no_utf8mb4.cnf file:
collation-server = utf8_general_ci
character-set-server = utf8
But I cannot get the collation_connection as latin1_swedish_ci. How could I achieve that?
I exported my database from the hosting and imported it into ddev, but with the current configuration, every time I login into the backend, I receive an error like this:
An exception occurred while executing 'INSERT INTO sys_log (userid, type, action, error, details_nr, details, log_data, tablename, recuid, IP, tstamp, event_pid, NEWid, workspace) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params [1, 255, 1, 0, 1, "User %s logged in from %s (%s)", "a:3:{i:0;s:30:\"xxx#xxx.com\";i:1;s:10:\"172.18.0.6\";i:2;s:0:\"\";}", "", 0, "172.18.0.6", 1564691070, -1, "", -99]: Field 'request_id' doesn't have a default value
Has anyone experienced this issue?
My MariaDB version over my ddev instance is 10.1.37-MariaDB.

PostgreSQL, Perl, DBD and the Insert command with "TO_TIMESTAMP"

I'm programming a script which queries some devices and writes the data to a PostgreSQL database.
The data includes a date which is formatted like 31.12.2015 13:45:00. The database uses the DateType "German" and the column is of the type Timestamp without timezone.
I always get this error message
DBD::Pg::st execute failed: ERROR: invalid input syntax for type timestamp:
"TO_TIMESTAMP('19.06.2015 11:24:20','DD.MM.YYYY HH24:MI:SS')::timestamp without time zone"
at temp_alcp2e_db.pl line 80, line 289.
I'm using this code, where $date_db has the date value:
$date_db = 'TO_TIMESTAMP(\'' . $date_db . '\',\'DD.MM.YYYY HH24:MI:SS\')::timestamp without time zone';
$stmt = $dbh->prepare("INSERT INTO rifutemp (\"USER_LINK_ID\", \"IP\", \"DATUM\", \"TEMPERATURE\") VALUES (?, ?, ?, ?)");
$stmt->execute($key_bgtr, $key_ip, $date_db, $temperatur) or die $DBI::errstr;
Hopefully, someone can show me what I did wrong.
The function can (and must) be part of the prepared statement.
Re-write your code as follows:
$stmt =$dbh->prepare(q{
INSERT INTO rifutemp ("USER_LINK_ID","IP","DATUM","TEMPERATURE")
VALUES (?, ?,
TO_TIMESTAMP(?, 'DD.MM.YYYY HH24:MI:SS')::timestamp without time zone,
?)
});
$stmt->execute($key_bgtr,$key_ip,$date_db,$temperatur) or die $DBI::errstr;
Ok, I've found my problem / the source of the errors:
To manage the Database visually I'm using the "EMS SQL Manager Lite for PostgreSQL", and this nice GUI tool always sets the DateStyle options to "ISO, MDY".
I've just changed my code like this:
$dbh->do("SET datestyle = 'German'");
$stmt =$dbh->prepare("INSERT INTO rifutemp (\"USER_LINK_ID\",\"IP\",\"DATUM\",\"TEMPERATURE\")
VALUES (?, ?, ?, ?)");
$stmt->execute($key_bgtr,$key_ip,$date_db,$temperatur) or die $DBI::errstr;
and set the $date_db variable to the correct format:
$date_db = Time::Piece->new->strftime('%d.%m.%Y %H:%M:%S');
and now everything works fine!

Calling prepare with mysqli - SQL syntax error

$q2 = "UPDATE `tasks` SET `title` = ?, task = ?, rules = ?, media = ?, type = ?, xp = ?, available = ?, timestamp = ? WHERE id = ?";
if ($stmt = $mysqli->prepare($q2)) {
$stmt->bind_param("sssssissi", $_POST["tasktitle"], $_POST["editor"], $_POST["rules"], serialize($_POST["media"]), $_POST["type"], $_POST["xp"], $a = 0, strtotime("now"), $_GET['id']);
$stmt->execute();
$stmt->close();
}
$r = $mysqli->query($q2) or die($mysqli->error);
I got this error msg:
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 '?, task = ?, rules = ?, media = ?, type = ?, xp = ?, available = ?, timestamp = ' at line 1
What is problem, and how can i solve it?
I'm pretty certain it's coming from the call to $mysqli->query() which needs a properly escaped query (ie, none of that nice safe parameter stuff). That explains why it's complaining at the first ?.
Quick way to check is to actually comment out the entire if statement and se if the error still appears. If so, you know it's the query rather than the prepared statement execution.
My question to you is: why are you executing the prepared statement and then trying to run it again as a query?
I think you'll find the execute does your update quite well enough. Get rid of the call to query and you should be fine.