Creating test objects in RSpec with FactoryGirl fails with Nested Attributes - sqlite

I have a Workout model that has many PerformedExercises, which has many PeformedSets. I can't get it to build an object in my test and I am not sure if it's SQLite3, or something else (it works fine outside of the testing environment).
I have the following factories:
FactoryGirl.define do
factory :workout do
title 'workout one'
performed_exercise
end
factory :performed_exercise do
exercise_id '2'
performed_set
end
factory :performed_set do
set_number '1'
end
end
My RSpec test looks like so (I've made it real simple so as to rule out any other issues inside the test):
it "is causing me to lose hair" do
wrkt = FactoryGirl.build(:workout)
end
When I run the test, I get the following error message:
Failure/Error: wrkt = FactoryGirl.build(:workout)
ActiveRecord::StatementInvalid:
SQLite3::ConstraintException: constraint failed:
INSERT INTO "performed_sets" ("created_at", "notes", "performed_exercise_id", "reps", "set_number", "updated_at", "weight")
VALUES (?, ?, ?, ?, ?, ?, ?)
Any help would be greatly appreciated!

Don't set the exercise id. Let SQLite handle the id's for you.
factory :performed_exercise do
performed_set
end

Related

Using WHERE NOT EXISTS in Sqlite returns syntax error

(This relates to a Discord bot using Discord.js and sqlite v3, NOT sqlite3)
I'm currently trying to use WHERE NOT EXISTS to add a row to my Sqlite table, but only if there isn't a row where "serverid" is the ID of the current server and the type spam already.
I tried it with this:
sql.run(`INSERT INTO filters WHERE NOT EXISTS(SELECT 1 FROM filters WHERE serverid = "${msg.guild.id}" AND type = "Spam") (serverid, type, active, action, time) VALUES (?, ?, ?, ?, ?)`, msg.guild.id, `Spam`, 0, `delete`, 60)
This works if there ISN'T a row with that ID and type yet, but as soon as it does exist, I get a "syntax error at: WHERE".
It doesn't tell me which WHERE the problem is, and I double checked the syntax multiple times and it should be fine.
Does this not work in sqlite? Or did I get the syntax wrong?
The syntax of the query is wrong.
You should use INSERT ... SELECT instead of INSERT ... VALUES:
INSERT INTO filters (serverid, type, active, action, time)
SELECT ?, ?, ?, ?, ?
WHERE NOT EXISTS(SELECT 1 FROM filters WHERE serverid = "${msg.guild.id}" AND type = "Spam")`

Python 3 variable that contains questionmarks

I'm trying to make a python3 sqlite3 database function that determines the amount of column with a for loop. During this for loop I want to add a "?" to a variable for each column.
So what I'm trying to do now is create a list from which I remove the quotes and brackets afterwards but using the .strip() and .replace() method don't seem to work for me either.
lijst = []
lijst.append("?")
lijst.append("?")
lijst.replace('"', '')
lijst.strip([])
print(lijst)
In the end I want it to look a bit like this (?, ?, ?).
lijst is a list, not a string. You can't treat the two interchangeably. Instead, you can construct a string directly. Where n in the number of ? you want in your final string:
n = 3
result = "({})".format(", ".join("?"*n))
print(result)
# (?, ?, ?)

How to use RowMapper to insert record into table?

How to insert data into table using row mapper?
I am trying this:
Employee user1 = jtemplate.queryForObject("INSERT INTO employee(id, name,salary) VALUES(10,'ABC',12333);",new BeanPropertyRowMapper<Employee>(Employee.class));
It gives me bad SQL grammar error.
But query works in SQL developer. What I am doing wrong?
Exception in thread "main" org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [INSERT INTO employee(id, name,salary) VALUES(99,'ABC',12333)]; nested exception is java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:411)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:466)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:476)
at com.cts.orm.rowmapper.Test.main(Test.java:29)
Caused by: java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:445)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:389)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:382)
at oracle.jdbc.driver.T4CTTIfun.processError(T4CTTIfun.java:600)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:450)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)
at oracle.jdbc.driver.T4C8Odscrarr.doODNY(T4C8Odscrarr.java:98)
at oracle.jdbc.driver.T4CStatement.doDescribe(T4CStatement.java:805)
at oracle.jdbc.driver.OracleStatement.describe(OracleStatement.java:3978)
at oracle.jdbc.driver.OracleResultSetMetaData.<init>(OracleResultSetMetaData.java:55)
at oracle.jdbc.driver.OracleResultSetImpl.getMetaData(OracleResultSetImpl.java:175)
at org.springframework.jdbc.core.BeanPropertyRowMapper.mapRow(BeanPropertyRowMapper.java:240)
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:93)
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60)
at org.springframework.jdbc.core.JdbcTemplate$1QueryStatementCallback.doInStatement(JdbcTemplate.java:455)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:400)
... 3 more
NamedParameterJdbcTemplate does what you want:
namedParameterJdbcTemplate.update(
"INSERT INTO employee(id, name, salary) VALUES (:id, :name, :salary)",
new BeanPropertySqlParameterSource(Employee.class));
removing the semi colon at the end of the statement should solve the problem use it like this. when using the jdbc templates it is not good to use semicolon at the end of sql statements
Employee user1 = jtemplate.queryForObject("INSERT INTO employee(id, name,salary) VALUES(10,'ABC',12333)",new BeanPropertyRowMapper<Employee>(Employee.class));
try using it like
jtemplate.update("INSERT INTO Employee(ID, NAME, Salary) VALUES (?, ?, ?)",
new Object[] { employee.getId(), employee.getName(), employee.getSalary() });
i am using this and it works correctly and displays no errors
Try this:
jdbcTemplate.update("INSERT INTO employee(id, name,salary) VALUES(?,?,?)", 10, "ABC", 12333);

ASP.NET and SQL - inserting data into more than one table?

So I know similar questions have been asked before, but I couldn't find a clear answer for my specific situation. I'm using ASP.NET (in Visual Web Developer) and I need to insert data from one form into two separate tables. This is my data source:
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/courseinfo.mdb"
SelectCommand="SELECT * FROM [tableCourse], [tableFaculty]"
InsertCommand="INSERT INTO [tableCourse]
([department], [name_first], [name_last], [prefix],
[course_number], [credits], [title], [description])
VALUES (?, ?, ?, ?, ?, ?, ?, ?); INSERT INTO [tableFaculty] ([name_first], [name_last], [phone], [email])
VALUES (?, ?, ?, ?)">
So you see I've tried using two insert statements, and it just comes back with an error saying there are extra characters after the SQL statement. I've tried taking out the semi-colon and then it says I'm missing a semi-colon. Is it possible to insert to two tables at once using this control? And if not, how do I work around this?
UPDATE:
Okay, tried it in the codebehind, but I don't think I did it right, now it's giving me this error:
Server Error in '/CCC' Application.
Index or primary key cannot contain a Null value.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: Index or primary key cannot contain a Null value.
Source Error:
Line 87:
Line 88: AccessDataSource1.InsertCommand = "INSERT INTO [tableCourse] ([department], [name_first], [name_last], [prefix], [course_number], [credits], [title], [description]) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
Line 89: AccessDataSource1.Insert()
Line 90:
Line 91: AccessDataSource1.InsertCommand = "INSERT INTO [tableFaculty] ([name_first], [name_last], [phone], [email]) VALUES (?, ?, ?, ?)"
Line 89 is the one that's highlighted. So I'm thinking it's attempting to insert but for some reason the values are null, it isn't taking the values from the text boxes.
I probably left something obvious out, I don't know, I'm really new at this.
Why don't you give it a try at the codebehind?
AccessDataSource1.InsertCommand = "First INSERT Statement";
AccessDataSource1.Insert();
AccessDataSource1.InsertCommand = "Second INSERT Statement";
AccessDataSource1.Insert();

SQLite error: 'could not convert text value to numeric value.'

I've found a work-around, but I am completely perplexed by an issue I ran into with Adobe Air and SQLite. An UPDATE query that I believe worked correctly earlier in the development process suddenly started failing with the error details:'could not convert text value to numeric value.', operation:'execute', detailID:'2300'. Several hours later I found that if I included a pretty irrelevant column in the query, setting it to an arbitrary value, the problem went away. As luck would have it, this did not affect the business logic in any meaningful way, so I'm going to leave it as is. However, I detest mysteries like this. Can anyone think of what might have happened?
(Edit: Sorry, I made a mistake in my code. The last two queries were identical in my original post. In fact, the UPDATE query only worked when I also added locked = null or locked = 0 to the query. If I didn't set this value, the query would fail. I did just about everything I could to get around this, including rebuilding the database file.)
Here's the table definition:
CREATE TABLE cars (
car_id INTEGER PRIMARY KEY AUTOINCREMENT DEFAULT NULL,
cargroup_id NUMERIC,
starting_ordinal NUMERIC,
ending_ordinal NUMERIC,
locked NUMERIC
);
This query has always worked:
var query = new Query(
"UPDATE cars SET locked = (car_id = ?) WHERE cargroup_id = ?",
[intCarId,intCargroupId],
success,failure
);
This query failed with the above error ([edit]):
var query = new Query(
"UPDATE cars SET starting_ordinal = ?, ending_ordinal = ?, cargroup_id = ? WHERE car_id = ?",
[
parseInt(objPayout.starting_ordinal,10),
parseInt(objPayout.ending_ordinal,10),
parseInt(objPayout.cargroup_id,10),
parseInt(objPayout.car_id,10)
],
success,failure
);
I solved the problem by changing the query to this:
var query = new Query(
"UPDATE cars SET starting_ordinal = ?, ending_ordinal = ?, cargroup_id = ?, locked = null WHERE car_id = ?",
[
parseInt(objPayout.starting_ordinal,10),
parseInt(objPayout.ending_ordinal,10),
parseInt(objPayout.cargroup_id,10),
parseInt(objPayout.car_id,10)
],
success,failure
);

Resources