Microsoft.EntityFrameworkCore.Database.Command Failed executing DbCommand (size=-1) - entity-framework

I don't know why parameter 8 has size of -1. In EntityFramework, this property has a maxlength of 75 and the column in the database is a nvarchar(75). It's the only parameter to have wrong size.
[2022-11-01 00:13:30.381 -04:00] [Error] [AC-PEL1:73] [Microsoft.EntityFrameworkCore.Database.Command] Failed executing DbCommand ("13"ms) [Parameters=["#p0='?' (Size = 10), #p1='?' (DbType = DateTime2), #p2='?' (DbType = DateTime2), #p3='?' (DbType = DateTime2), #p4='?' (DbType = DateTime2), #p5='?' (DbType = DateTime2), #p6='?' (Size = 100), #p7='?' (DbType = Guid), #p8='?' (Size = -1), #p9='?' (DbType = Int32), #p10='?' (Size = 100), #p11='?' (DbType = Boolean), #p12='?' (Size = 2000), #p13='?' (Size = 100), #p14='?' (Size = 2000), #p15='?' (Size = 2000), #p16='?' (Size = 2000)"], CommandType='Text', CommandTimeout='30']"
""SET NOCOUNT ON; INSERT INTO [Pel].[DemandeInterventions] ([CodeIntervention], [DateCourriel], [DateDerniereModifExterne], [DateEffectuee], [DateIntervention], [DatePrevue], [Description], [EmailId], **[Etat]**, [IdDemande], [IntervenantExterne], [InterventionExterne], [MessageCourriel], [NomEmploye], [NoteClient], [NoteCourriel], [NoteInterne]) VALUES (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9, #p10, #p11, #p12, #p13, #p14, #p15, #p16); SELECT [Id] FROM [Pel].[DemandeInterventions] WHERE ##ROWCOUNT = 1 AND [Id] = scope_identity();"
I want to insert data in my database and i want parameter 8 to be like all others parameters the mix size of the property (75) not -1

Related

Summation graph over tree in PostgreSQL

I have salaries table and a tree with departments (child, parent). Need to go over the graph and calculate every summation vertex. The output I need - summation of all child nodes. The issue looks like the request is double counting values.
Test data:
CREATE TABLE deps (
id serial,
child varchar,
parent varchar);
CREATE TABLE salaries (
name varchar,
salary numeric);
INSERT INTO salaries(name, salary) VALUES
('manager1', 100),
('manager2', 100),
('manager3', 100),
('manager4', 100),
('manager5', 100),
('manager6', 100),
('manager7', 100),
('manager8', 100),
('manager9', 100),
('engeneer1', 100),
('engeneer2', 100),
('engeneer3', 100),
('engeneer4', 100),
('engeneer5', 100),
('engeneer6', 100),
('engeneer7', 100),
('engeneer8', 100),
('engeneer9', 100),
('engeneer10', 100),
('accountant1', 100),
('accountant2', 100),
('accountant3', 100),
('accountant4', 100);
insert INTO deps(child, parent) VALUES
('manager1', 'management'),
('manager2', 'management'),
('manager3', 'management'),
('manager4', 'management'),
('management_team1', 'management'),
('management_team1_1', 'management_team1'),
('management_team1_2', 'management_team1'),
('manager5', 'management_team1_1'),
('manager6', 'management_team1_1'),
('manager7', 'management_team1'),
('manager8', 'management_team1_2'),
('manager9', 'management_team1_2'),
('engeneer1', 'it'),
('engeneer2', 'it'),
('engeneer3', 'it'),
('engeneer4', 'it'),
('it_dep1', 'it'),
('it_dep2', 'it'),
('engeneer5', 'it_dep1'),
('engeneer6', 'it_dep1'),
('engeneer7', 'it_dep2'),
('engeneer8', 'it_dep2'),
('it_dep3', 'it_dep2'),
('engeneer9', 'it_dep3'),
('engeneer10', 'it_dep3'),
('accountant1', 'accounts'),
('accountant2', 'accounts'),
('accountant3', 'accounts'),
('accountant4', 'accounts'),
('management', NULL),
('accounts', NULL),
('it', NULL);
Request:
WITH RECURSIVE tree ("depth", parent, child) as(
SELECT
0,
parent,
child
FROM deps
WHERE parent IS NULL
UNION
SELECT
"depth" + 1,
tree.child,
deps.child
FROM tree JOIN deps ON tree.child = deps.parent
),
graph (child, parent, "depth", value) as(
-- non recursive
SELECT
tree.child,
tree.parent,
tree."depth",
salaries.salary -- outbound amount FROM node which IS equal TO salary AT this depth
FROM
tree JOIN salaries ON salaries.name = tree.child
WHERE tree."depth" = (SELECT max("depth") FROM tree) -- we START FROM deepest LEVEL OF yierarchy
UNION
-- recursive
SELECT
current_tree.child,
current_tree.parent,
current_tree."depth",
COALESCE(current_tree.salary,
sum(graph.value) OVER (PARTITION BY current_tree.child)
) -- outbound amount FROM node which IS equal TO SUM of ALL incoming amounts
FROM
graph,
LATERAL (SELECT * FROM tree LEFT JOIN salaries ON salaries.name = tree.child WHERE tree."depth" = graph."depth" - 1) AS current_tree
LEFT JOIN LATERAL (SELECT * FROM tree WHERE tree."depth" = graph."depth") AS previous_tree
ON current_tree.child = previous_tree.parent
-- WHERE graph."depth" = (SELECT max("depth") FROM graph)
)
SELECT * FROM graph
WHERE graph."depth" = (SELECT max("depth") FROM graph)
gives error since double calling of graph table is not allowed
DB Fiddle sample
I expect to see 32 relations corresponding to initial tree with sums as values of all child nodes.

int4range, NOT IN (VALUES), ON NOT (with LEFT JOIN) in QueryDSL 4

I would like to know, how to make a int4range / NOT IN (VALUES) / ON NOT (with LEFT JOIN) in QueryDSL 4.
I've writte this SQL request :
SELECT DISTINCT ON (numero_semaine, jour_semaine)
numero_semaine, jour_semaine, heure_debut, heure_fin, id_box
FROM (
SELECT po.* FROM (
(SELECT DISTINCT ON (numero_semaine, jour_semaine)
numero_semaine, jour_semaine, heure_debut, heure_fin, id_box
FROM accueil.semaine_type_box
INNER JOIN accueil.plage_ouverture
ON accueil.plage_ouverture.id_semaine_type = accueil.semaine_type_box.id_semaine_type
INNER JOIN accueil.semaine_type
ON accueil.semaine_type.id = accueil.semaine_type_box.id_semaine_type
INNER JOIN accueil.box
ON accueil.box.id = accueil.semaine_type_box.id_box
WHERE semaine_type_box.numero_semaine >= 48
AND semaine_type_box.numero_semaine <= 52
AND (numero_semaine, jour_semaine)
---->NOT IN (VALUES (48,1), (48,2), (48,3), (48,4), (52,6), (52,7))<----
AND semaine_type.site = 'UR130'
AND box.ouvert_cotisant = TRUE
ORDER BY numero_semaine, jour_semaine, heure_debut
)
UNION ALL
(SELECT DISTINCT ON (numero_semaine, jour_semaine)
extract(week from plage_exceptionnelle.date) as numero_semaine,
extract(isodow from plage_exceptionnelle.date) as jour_semaine,
heure_debut, heure_fin, id_box
FROM accueil.plage_exceptionnelle
INNER JOIN accueil.box ON
accueil.box.id= accueil.plage_exceptionnelle.id_box
WHERE plage_exceptionnelle.date >= '2018-11-30'
AND plage_exceptionnelle.date <= '2018-12-28'
AND ouverte = TRUE
AND box.site = 'UR130'
AND box.ouvert_cotisant = TRUE
ORDER BY numero_semaine, jour_semaine, heure_debut
)
) po
LEFT JOIN (
SELECT
extract(week from plage_bloquee.date) as numero_semaine,
extract(isodow from plage_bloquee.date) as jour_semaine,
heure_debut, heure_fin, id_box
FROM accueil.plage_bloquee
INNER JOIN accueil.box ON accueil.box.id = accueil.plage_bloquee.id_box
WHERE box.site = 'UR130'
AND box.ouvert_cotisant = TRUE
) pb
---->ON NOT(po.jour_semaine = pb.jour_semaine<----
---->AND int4range(po.heure_debut, po.heure_fin) && int4range(pb.heure_debut, pb.heure_fin)<----
AND po.id_box = pb.id_box
AND po.numero_semaine = pb.numero_semaine
)
WHERE pb.id_box IS NOT NULL
) end_table
ORDER BY numero_semaine,jour_semaine,heure_debut
What is the way to do this SQL request ?
I've writte this, but I don't find the way to writte a not in, on not with left join, and int4range doesn't exist with QueryDSL 4 :
public List<PlageDisponibleWS> findDayAvailableDao(String organisme, String site, MediaEnum media) {
final LocalDate startDate = LocalDate.now();
final short startWeekOfWeekYear = (short) startDate.getWeekOfWeekyear();
final short startDay = (short) startDate.getDayOfWeek();
final LocalDate endDate = startDate.plusMonths(1);
final short endWeekOfWeekYear = (short) endDate.getWeekOfWeekyear();
final int MONDAY_START_DAY = 1;
final int TUESDAY_START_DAY = 2;
final int WEDNESDAY_START_DAY = 3;
final int THURSDAY_START_DAY = 4;
final int FRIDAY_START_DAY = 5;
final int SATURDAY_START_DAY = 6;
final int SUNDAY_START_DAY = 7;
PostgreSQLQuery<Tuple> plagesOuvertes = queryFactory
.select(qSemaineTypeBox.numeroSemaine, qSemaineTypeBox.idBox, qPlageOuverture.jourSemaine,
qPlageOuverture.heureDebut, qPlageOuverture.heureFin)
.distinctOn(qSemaineTypeBox.numeroSemaine, qPlageOuverture.jourSemaine).from(qSemaineTypeBox)
.innerJoin(qPlageOuverture).on(qPlageOuverture.idSemaineType.eq(qSemaineTypeBox.idSemaineType))
.innerJoin(qSemaineType).on(qSemaineType.id.eq(qSemaineTypeBox.idSemaineType)).innerJoin(qBox)
.on(qBox.id.eq(qSemaineTypeBox.idBox)).where(qSemaineTypeBox.numeroSemaine.goe(startWeekOfWeekYear))
.where(qSemaineTypeBox.numeroSemaine.loe(endWeekOfWeekYear))
// NOT IN (VALUES (startWeekOfWeekYear,MONDAY_START_DAY), (startWeekOfWeekYear,TUESDAY_START_DAY),
// (startWeekOfWeekYear,WEDNESDAY_START_DAY), (startWeekOfWeekYear,THURSDAY_START_DAY),
// (endWeekOfWeekYear,SATURDAY_START_DAY), (endWeekOfWeekYear,SUNDAY_START_DAY)) ??
.where(qSemaineType.site.eq(site)).where(qBox.ouvertCotisant.eq(true))
.orderBy(qSemaineTypeBox.numeroSemaine.asc(), qPlageOuverture.jourSemaine.asc(),
qPlageOuverture.heureDebut.asc());
PostgreSQLQuery<Tuple> plagesExceptionnelles = queryFactory
.select(qPlageExceptionnelle.date.week().as("numero_semaine"),
qPlageExceptionnelle.date.dayOfWeek().as("jour_semaine"), qPlageExceptionnelle.heureDebut,
qPlageExceptionnelle.heureFin, qPlageExceptionnelle.idBox)
.distinctOn(qSemaineTypeBox.numeroSemaine, qPlageOuverture.jourSemaine).from(qPlageExceptionnelle)
.innerJoin(qBox).on(qBox.id.eq(qPlageExceptionnelle.idBox))
.where(qPlageExceptionnelle.date.goe(startDate)).where(qPlageExceptionnelle.date.loe(endDate))
.where(qPlageExceptionnelle.ouverte.eq(true)).where(qBox.site.eq(site))
.where(qBox.ouvertCotisant.eq(true)).orderBy(qSemaineTypeBox.numeroSemaine.asc(),
qPlageOuverture.jourSemaine.asc(), qPlageOuverture.heureDebut.asc());
PostgreSQLQuery<Tuple> plagesBloquees = queryFactory
.select(qPlageBloquee.date.week().as("numero_semaine"),
qPlageBloquee.date.dayOfWeek().as("jour_semaine"), qPlageBloquee.heureDebut,
qPlageBloquee.heureFin, qPlageBloquee.idBox)
.from(qPlageBloquee).innerJoin(qBox).on(qBox.id.eq(qPlageBloquee.idBox)).where(qBox.site.eq(site))
.where(qBox.ouvertCotisant.eq(true));
#SuppressWarnings("unchecked")
Expression<Tuple> unionSubQuery = queryFactory.query().unionAll(plagesOuvertes, plagesExceptionnelles)
.as("po");
final PathBuilder<Object> aliasPb = new PathBuilder<>(Object.class, "pb");
PostgreSQLQuery<Tuple> leftJoinSubQuery = queryFactory.select(unionSubQuery)
.leftJoin(plagesBloquees, aliasPb)
// ON NOT
// INT4RANGE
;
final PathBuilder<Object> aliasEnd = new PathBuilder<>(Object.class, "end_table");
query = queryFactory
.select(Projections.constructor(PlageDisponibleWS.class, qSemaineTypeBox.numeroSemaine,
qSemaineTypeBox.idBox, qPlageOuverture.jourSemaine, qPlageOuverture.heureDebut,
qPlageOuverture.heureFin))
.distinctOn(qSemaineTypeBox.numeroSemaine, qPlageOuverture.jourSemaine)
.from(leftJoinSubQuery, aliasEnd).orderBy(qSemaineTypeBox.numeroSemaine.asc(),
qPlageOuverture.jourSemaine.asc(), qPlageOuverture.heureDebut.asc())
.fetch();
return query;
}
So please have you any idea to solve my problems ?
Thanks a lot in advance.
For "in values" construction with multiple columns you can try this:
.where(list(table.column1, table.column2).
in(list(select(constant("aaa"), constant("bbb")),
select(constant("ccc"), constant("ddd")),
select(constant("eee"), constant("fff")))))
Function "list" and "select comes from these imports:
import static com.querydsl.core.types.dsl.Expressions.*;
import static com.querydsl.sql.SQLExpressions.*;
For "left join + not", try this:
.from(table1)
.leftJoin(table2)
.on(table1.id.ne(table2.id))
Unfortunatly I am not familar with int4range function, hovewer you can try to use template expression for custom database functions:
Expressions.template(Integer.class, "custom_db_function({0}, {1})", 10, 20);

Null values in qtablewidget

I develop a desktop application on PYQT5 with integration of posgtresql. I stumbled over the situation that the table does not display the values:
source code:
def createTable(self):
self.tableWidget = QTableWidget()
conn = psycopg2.connect('host=localhost port=5432 dbname=postgres user=postgres password=12345678')
cursor = conn.cursor()
query = cursor.execute("SELECT * FROM wave_params")
result = cursor.fetchall()
for i in result:
print(i)
rows = len(result)
columns = len(result[0])
self.tableWidget.setColumnCount(columns)
self.tableWidget.setRowCount(rows)
index = 0
while query != None:
self.tableWidget.setItem(index,0, QTableWidgetItem(query.result[0]))
# self.tableWidget.setItem(index, 1, QTableWidgetItem(str(query.value(1))))
# self.tableWidget.setItem(index, 2, QTableWidgetItem(str(query.value(2))))
index = index + 1
# table selection change
self.tableWidget.doubleClicked.connect(self.on_click)
#pyqtSlot()
def on_click(self):
print("\n")
for currentQTableWidgetItem in self.tableWidget.selectedItems():
print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())
I can not understand. what is the problem?
Thanks!
the cursor object has no attribute result.
in your code result is a list of tuples containing the return value of cursor.fetchall() and query is the return value of cursor.execute(). cursor.execute() returns always None
(see documentation). You only need to loop over result, here 2 examples:
def createTable(self):
self.tableWidget = QTableWidget(self)
psycopg2.connect('host=localhost port=5432 dbname=postgres user=postgres password=12345678')
cursor = conn.cursor()
query = cursor.execute("SELECT * FROM ladestelle")
result = cursor.fetchall()
rows = len(result)
columns = len(result[0])
self.tableWidget.setColumnCount(columns)
self.tableWidget.setRowCount(rows)
for i, r in enumerate(result):
self.tableWidget.setItem(i, 0, QTableWidgetItem(r[0]))
self.tableWidget.setItem(i, 1, QTableWidgetItem(str(r[1])))
self.tableWidget.setItem(i, 2, QTableWidgetItem(str(r[2])))
'''
# or simpler
for r in range(rows):
for c in range(columns):
self.tableWidget.setItem(r, c, QTableWidgetItem(str(result[r][c])))
'''
self.tableWidget.doubleClicked.connect(self.on_click)

Entity Framework intermittently set the byte field into 255

I have a piece of code that inserts into a table. Simply, I have a table with structure
Table1:
Id int PK
Type tinyint
Status tinyint
After digging in our PROD, I observed that EF might be intermittently defaulting the value to 255 when the value should range (1-3). I understand 255 is the max value for tinyint in SQL Server but I have no defaults in both table definition and in EDMX.
Usage:
//OUTAGE_TYPE
public enum OUTAGE_TYPE
{
Unknown = -1,
SwitchingPlan = 1,
PlannedIncident = 2,
UnplannedIncident = 3
}
//CREATE INSTANCE
var outage = new Outage
{
OutageTypeId = (byte)OUTAGE_TYPE.SwitchingPlan,
OutageStatusId = (byte)OUTAGE_STATUS.Approved,
IncidentRID = incident.RID,
WorkRID = incident.WorkRID,
ETR = incident.ETR,
DateInserted = Time.Now(),
DateUpdated = Time.Now()
};
Captured SQL:
INSERT [dbo].[Outage]([OutageTypeId], [OutageStatusId], [IncidentRID], [WorkRID], [ETR], [DateInserted], [DateUpdated])
VALUES (#0, #1, #2, NULL, #3, #4, #5)
SELECT [Id]
FROM [dbo].[Outage]
WHERE ##ROWCOUNT > 0 AND [Id] = scope_identity()
-- #0: '255' (Type = Byte, Size = 1)
-- #1: '1' (Type = Byte, Size = 1)
-- #2: 'INC 11000700' (Type = String, Size = 255)
-- #3: '05-08-2016 10:05:52' (Type = DateTime2)
-- #4: '05-08-2016 22:05:22' (Type = DateTime2)
-- #5: '05-08-2016 22:05:22' (Type = DateTime2)
-- Executing at 06-08-2016 00:06:00 +02:00
Error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Outage_OutageType". The conflict occurred in database "ONSP", table "dbo.OutageType", column 'Id'.
I was not able to reproduce on my local machine, maybe you guys have experienced this before. Many thanks.
After my colleague and me digging around, we found the root cause of this problem.
First -1, is not a valid value for a byte and direct conversion will not throw exception but will yield to byte.MaxValue
void Main()
{
var type = OUTAGE_TYPE.Unknown;
var result = (byte)type;
//result = 255!!!
Console.WriteLine(result);
}
public enum OUTAGE_TYPE
{
Unknown = -1,
SwitchingPlan = 1,
PlannedIncident = 2,
UnplannedIncident = 3
}

How do I insert a record that has a serial in a PostgreSQL table?

I want to add rows to a table with a serial "ID".
I need to NOT supply ID for in to be incrementd automatically, but I can't seem to leave it out:
NpgsqlCommand cmd = new NpgsqlCommand("insert into \"Min_Bar_Price_Data\" values(:SEC_ID, :PX_OPEN, :PX_HIGH, :PX_LOW, :PX_LAST, :PX_VOLUME, :Date)", conn);
//cmd.Parameters.Add(new NpgsqlParameter("ID", DbType.Int32));
cmd.Parameters.Add(new NpgsqlParameter("SEC_ID", DbType.Int32));
cmd.Parameters.Add(new NpgsqlParameter("PX_OPEN", DbType.Double));
cmd.Parameters.Add(new NpgsqlParameter("PX_HIGH", DbType.Double));
cmd.Parameters.Add(new NpgsqlParameter("PX_LOW", DbType.Double));
cmd.Parameters.Add(new NpgsqlParameter("PX_LAST", DbType.Double));
cmd.Parameters.Add(new NpgsqlParameter("PX_VOLUME", DbType.Double));
cmd.Parameters.Add(new NpgsqlParameter("Date", DbType.DateTime));
This is the table:
CREATE TABLE "Min_Bar_Price_Data"
(
"ID" integer NOT NULL DEFAULT nextval('"Price_Data_ID_seq"'::regclass),
"Sec_ID" integer NOT NULL,
"PX_OPEN" double precision,
"PX_HIGH" double precision,
"PX_LOW" double precision,
"PX_LAST" double precision,
"PX_VOLUME" double precision,
"Date" timestamp without time zone NOT NULL,
CONSTRAINT "Min_Bar_Price_Data_pkey" PRIMARY KEY ("Sec_ID", "Date")
)
WITH (
OIDS=FALSE
);
Then I fill in parameters:
//cmd.Parameters["ID"].Value = ID;
cmd.Parameters["SEC_ID"].Value = sec_ID;
cmd.Parameters["PX_OPEN"].Value = 0.0;
cmd.Parameters["PX_HIGH"].Value = 0.0;
cmd.Parameters["PX_LOW"].Value = 0.0;
cmd.Parameters["PX_LAST"].Value = d.Close;
cmd.Parameters["PX_VOLUME"].Value = 1.0;
cmd.Parameters["Date"].Value = d.DT;
cmd.ExecuteNonQuery();
{"ERROR: 42804: column \"PX_VOLUME\" is of type double precision but expression is of type timestamp without time zone"}
You should explicitly specify columns list:
NpgsqlCommand cmd = new NpgsqlCommand(
"INSERT INTO \"Min_Bar_Price_Data\"" +
"(\"Sec_ID\",
\"PX_OPEN\",
\"PX_HIGH\",
\"PX_LOW\",
\"PX_LAST\",
\"PX_VOLUME\",
\"Date\")" +
"VALUES" +
"(:SEC_ID,
:PX_OPEN,
:PX_HIGH,
:PX_LOW,
:PX_LAST,
:PX_VOLUME,
:Date)", conn);