Error: table data has 1 columns but 3 values were supplied Unable to execute statement - sql

I'm testing this simple database program using a QML project:
Window {
visible: true
width: 640; height: 480
title: qsTr("SQL Example")
property var db
property int ident: 0
TextField {
id: field
placeholderText: qsTr("Enter Your Name")
hoverEnabled: true
}
Button {
text: "Next"
anchors.top: field.bottom
onClicked: storeData(field.displayText)
}
Component.onCompleted: initDatabase()
function initDatabase() {
db = LocalStorage.openDatabaseSync("data", "1.0", "Save names", 1000000)
db.transaction( function(tx)
{ tx.executeSql('CREATE TABLE IF NOT EXISTS data (id INTEGER, name TEXT, mode TEXT)') })
}
function storeData(username) {
db.transaction( function(tx) {
tx.executeSql('INSERT INTO data VALUES (?, ?, ?)', [ident, username, ""])
ident++ })
}
}
When I hit the Next button, after entering a name, I get this error message:
qrc:/main.qml:36: Error: table data has 1 columns but 3 values were supplied Unable to execute statement
Seemingly everything is right but I don't know why I get this error!

The query that you have.
INSERT INTO data VALUES (?, ?, ?)
The query that must be used as a better practice
INSERT INTO data (col1, col2, col3) VALUES (?, ?, ?)
Thing to note
Check if the table is already present in the database. That may be the reason why the create table statement is not executing with three column definition. If so remove the table and execute the code it will work.

Related

Insert column at the first position in grid

I am trying to insert row selection at the first position of grid but it always ends up among hidden columns. I did the same thing with delete button column and it worked just fine.
protected getColumns(): Slick.Column[] {
var cols = super.getColumns();
cols.unshift({
field: 'Delete Row',
name: '',
format: ctx => '<a class="inline-action delete-row" title="delete">' +
'<i class="fa fa-trash-o text-red"></i></a>',
width: 24,
minWidth: 24,
maxWidth: 24,
visible: true
});
cols.unshift(Serenity.GridRowSelectionMixin.createSelectColumn(() => this.rowSelection));
return cols;
The problem is not incorrect implementation of selection row. I know that because I tried it with different columns with same results. I also tried to set "visible" to true
Any ideas? Thanks
This code will make your selection column stay at first position
protected getPersistedSettings() {
let setting = super.getPersistedSettings();
let idCol = Q.tryFirst(setting.columns, x => x.id == "__select__");
if (idCol) {
setting.columns.splice(setting.columns.indexOf(idCol), 1);
setting.columns.splice(0, 0, idCol);
}
return setting;
}
But make sure that the selection is not in hidden list
The problem was that persistence of data was turned on with this function
protected getPersistanceStorage(): Serenity.SettingStorage {
return new Common.UserPreferenceStorage();
}

Sequelize Postgres - How to use ON CONFLICT for unique?

I am implementing sequelize into my NodeJS application. Before this, I was using a written INSERT query that used ON CONFLICT (field) DO NOTHING to handle not inserting records where a value needed to be unique.
const sql = 'INSERT INTO communications (firstname, lastname, age, department, campus, state, message_uuid) VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (message_uuid) DO NOTHING';
const values = [val.firstName, val.lastName, val.age, val.department, val.campus, val.state, message_uuid];
Is there support for this in sequelize where I can define the same thing within a model? Or perhaps a better way to handle it?
Essentially, if a record already exists in the table in the column with message_uuid = 123 and another record try's to insert that has that same value, it ignores it and does nothing.
You can use public static bulkCreate(records: Array, options: Object): Promise<Array> method with options.ignoreDuplicates.
Ignore duplicate values for primary keys? (not supported by MSSQL or Postgres < 9.5)
Besides, it's important to add a unique constraint for the message_uuid field on the model. So that the query will use ON CONFLICT DO NOTHING clause of Postgres.
For example, "sequelize": "^5.21.3" and postgres:9.6:
import { sequelize } from '../../db';
import { Model, DataTypes } from 'sequelize';
class Communication extends Model {}
Communication.init(
{
firstname: DataTypes.STRING,
lastname: DataTypes.STRING,
age: DataTypes.INTEGER,
message_uuid: {
type: DataTypes.INTEGER,
unique: true,
},
},
{ sequelize, tableName: 'communications' },
);
(async function test() {
try {
await sequelize.sync({ force: true });
// seed
await Communication.create({ firstname: 'teresa', lastname: 'teng', age: 32, message_uuid: 123 });
// test
await Communication.bulkCreate([{ firstname: 'teresa', lastname: 'teng', age: 32, message_uuid: 123 }], {
ignoreDuplicates: true,
});
} catch (error) {
console.log(error);
} finally {
await sequelize.close();
}
})();
Execution result:
Executing (default): DROP TABLE IF EXISTS "communications" CASCADE;
Executing (default): DROP TABLE IF EXISTS "communications" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "communications" ("id" SERIAL , "firstname" VARCHAR(255), "lastname" VARCHAR(255), "age" INTEGER, "message_uuid" INTEGER UNIQUE, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'communications' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "communications" ("id","firstname","lastname","age","message_uuid") VALUES (DEFAULT,$1,$2,$3,$4) RETURNING *;
Executing (default): INSERT INTO "communications" ("id","firstname","lastname","age","message_uuid") VALUES (DEFAULT,'teresa','teng',32,123) ON CONFLICT DO NOTHING RETURNING *;
Check the database, there is only one row as expected.
node-sequelize-examples=# select * from communications;
id | firstname | lastname | age | message_uuid
----+-----------+----------+-----+--------------
1 | teresa | teng | 32 | 123
(1 row)
see the new UPSERT feature in Sequelize v6:
https://sequelize.org/api/v6/class/src/model.js~model#static-method-upsert
Implementation details:
MySQL - Implemented with ON DUPLICATE KEY UPDATE`
PostgreSQL - Implemented with ON CONFLICT DO UPDATE.
If update data contains PK field, then PK is selected as the default conflict
key. Otherwise first unique constraint/index will be selected, which
can satisfy conflict key requirements.
SQLite - Implemented with ON CONFLICT DO UPDATE
MSSQL - Implemented as a single query using MERGE and WHEN (NOT) MATCHED THEN
as second argument of Model.create you can provide onConflict prop, please read the documentation

SQL query to search a String without key, in a Column which has only JSON data

I need to search a string, for example 'RecId' in a column which has only JSON data.
First Cell JSON Data:
{
"AuditedFieldsAndRelationships": null,
"AuditObjectChanges": false,
"CalculatedRules": {
"AuditHistoryDescription": {
"Calculated": "Always",
"CalculatedExpression": {
"Description": null,
"FieldRefs": ["RecId", "Rel_CIComponent_InstalledApplication_Name", "Rel_Software_Id", "Rel_Software_Name"]
}
}
}
}
Image:
Database: Microsoft SQL Server 2014
I got pretty similar problem solution in link but it is with respect to key
SELECT * FROM #table CROSS APPLY OPENJSON(Col,'$.Key') WHERE value ='SearchedString'
but it is showing error Invalid object name 'OPENJSON'
For that error, I tried the below solution given in link
SELECT compatibility_level FROM sys.databases WHERE name = 'DataBaseName';
But getting the below error:
Could someone help me out here.

Datatables - Inline editor only updates host table

I have a simple table using a left join:
Editor::inst( $db, 'enqitem', 'enqitemid')
->fields(
Field::inst( 'salstkitem.salsubid' ),
Field::inst( 'salstkitem.condition1' ),
Field::inst( 'enqitem.cost' )
)
->leftJoin('salstkitem', 'salstkitem.salsubid', '=', 'enqitem.itemid')
->where('enqitem.enqnr',141316)
->debug( true )
->process( $_POST )
->json();
In the editor, I have hidden the primary key of the non-host table:
editor = new $.fn.dataTable.Editor( {
ajax: "datatables.php",
table: "#example",
fields: [{
name: "salstkitem.salsubid",
type: "hidden"
},{
label: "Condition:",
name: "salstkitem.condition1"
},{
label: "Cost:",
name: "enqitem.cost"
}
]
});
I've set it to be editable inline:
$('#example').on( 'click', 'tbody td:not(:first-child)', function (e) {
editor.inline( this, {
onBlur: 'submit'
} );
});
When I edit inline, the cost updates successfully, as it's a member of the host table. However condition1 will not update.
If I select the EDIT button, both fields update successfully.
This issue is purely for inline editing.
Does anyone have any idea why?
The debug suggests it isn't trying to update at all. It is purely a SELECT query.
Allan, the creator of datatables got back to me:
If you are writing to a joined table rather than just the master table you need to have Editor submit the joined table's primary key as well (enqitem.enqitemid in this case I guess). When you are inline editing, by default it will only submit the edited field, but you can use the form-options object to change that:
editor.inline( this, {
onBlur: 'submit',
submit: 'allIfChanged'
} );
Regards,
Allan

Insert shows all empty values

I am rather new to this library (knex) and have run across a problem I have not been able to find a solution for on the interwebs.
Here is my Knex connection:
Knex({client: 'pg', connection: config.DB, searchPath:'syp,public', debug: true})
Here is my insert:
Knex('users')
.returning('id')
.insert(data)
.then(function(user) {
console.log(user);
}, function(err) {
console.log(err)
});
This is my data from the above query:
{
"first_name": "Kenneth",
"last_name": "Stowell",
"email": "ken#bakuahtsu.codes" }
The resulting error is:
code:"42703"
file:"parse_target.c"
length:119
line:"943"
name:"error"
position:"230"
routine:"checkInsertTargets"
severity:"ERROR"
Which would make sense as the debugger is showing the following as the sql:
sql:"insert into "users" ("first_name", "last_name", "email") values (?, ?, ?) returning "id""
I hope I am just making a newbie mistake but I cannot for the life of me figure out why. It appears to be making the bindings correctly but never applying them.
Any help appreciated!
The code 42703 is a postgres error code that means you're trying to insert data into a column that doesn't exist.