SQLiteException: near "If": syntax error - sqlite

I am converting a 'SQL Server 2008' stored procedure to 'SQLite'.
But facing problem with the following query:
If (Select Count(UserId) From Users Where RememberMe = 'True') > 1
Update Users Set RememberMe = 'False'
Select UserName From Users Where RememberMe = 'True'
While executing the above query in the 'SQLite Administrator' or 'SQLite Expert', I am getting the following error message:
Error occured: near "If": syntax error
I am a beginner in SQLite.
Please guide me.
Thanks & Regards,

Sqlite does not support if. You can use CASE instead of it.

SQLite doesn't support stored procedures.
But it looks like your code only updates the Users table to set RememberMe = 'False' for users that had it set to 'True'. If this is the case, then you don't need to do the If part at all. This should suffice:
UPDATE Users SET RememberMe = 'False' WHERE RememberMe = 'True';

Related

TypeOrm QueryBuilder dynamic auto delete function with crons job not working

Token for email verification is created with User registration and needs to be deleted from database within 24 hours with crons job help. In a delete function using query builder, token gets deleted only if date value is manually provided in form of string: {delDate: "2021-02-08T17:59:48.485Z" }. Here, all tokens with date before or equal 2021-02-08 get deleted, and is working fine. But thats a static input, manually put in hard code!
Since this must be a dynamic input, I set up variable 'delTime',which stores current date minus 24 hrs in it, but it seems .where condition will not take a variable as value, and will not delete, as: {delDate: deltime}. In fact, 'delDate' consoles exactly the info I need, but it will only work in form of string.
There is a ton of content online teaching how to delete stuff with a static value in typeorm querybuilder, but so hard to find with dynamic values....
How else can I make this work in a dynamic way ?
async delete(req: Request, res: Response){
try {
const tokenRepository = getRepository(Token);
var delTime = new Date();
delTime.setDate( delTime.getDate() - 1 );
console.log(delTime) //consoles 24 hors ago
await tokenRepository
.createQueryBuilder()
.delete()
.from(Token)
.where("tokenDate <= :deleteTime", { deleteTime: delTime})//value dynamically stored in variable does not delete
//.where("tokenDate <= :deleteTime", { deleteTime: "2021-02-08T18:01:10.489Z"})//static hard code value deletes
//.where("tokenDate <= :delTime", { delTime})//Variable put this way will not work either...
.execute();
} catch (error) {
res.status(404).send("Tokens not found");
return;
}
res.status(200).send('Tokens deleted successfuly');
}
Your parameterized query looks correct.
Switch on TypeOrm Query Logging to see the generated SQL, maybe you will be able to see what's going wrong. Paste the generated SQL into the SQL query console to debug.
Alternatively you can write your delete query without parameters and let Sqlite calculate current date -1 day:
.where("tokenDate <= DateTime('Now', '-1 Day'"); // for Sqlite
Note 1: Sqlite DateTime('Now') uses UTC time, so your tokenDate should use UTC also.
Note 2: This syntax is specific to Sqlite, you can do the same in other databases but the syntax is different, e.g. Microsoft SQL Server:
.where("tokenDate <= DATEADD(day, -1, SYSUTCDATETIME()); // for MS SQL Server

Trouble inserting data into sqlite database with JDBC

This is what my code currently looks like:
import java.sql.*
import java.sql.SQLException
class SqliteDB {
val conn = DriverManager.getConnection("jdbc:sqlite:cs2820-database.db")
fun createUser123(userID: String, password: String, adminStatus: String) {
val statement = conn.prepareStatement("INSERT INTO Users(id,pass,admin) VALUES(?,?,?)")
statement.setString(1, userID)
statement.setString(2,password)
statement.setString(3,adminStatus)
println("123")
statement.executeUpdate()
conn.commit()
println("User Created")
}
// create a user
fun createUser(userID: String, password: String, adminStatus: String) {
println("inside createUser")
val sql = "INSERT INTO Users(id,pass,admin) VALUES(?,?,?)"
Class.forName("org.sqlite.JDBC")
try {
conn.use { conn ->
conn.prepareStatement(sql).use { pstmt ->
pstmt.setString(1, userID)
pstmt.setString(2, password)
pstmt.setString(3, adminStatus)
pstmt.executeUpdate()
//conn.commit()
pstmt.close()
}
}
} catch (e: SQLException) {
println(e.message)
}
}
fun main(args: Array<String>) {
val db = SqliteDB()
db.createUser("Jim", "password", "false")
}
I have tested two different createUser methods and most everything I have tried will return the error [SQLITE_BUSY] The database file is locked (database is locked). I have several other methods within the same SqliteDB class that query data ("SELECT") that all work correctly, but every time I try to perform any kind of update of information I am given the same error. I am at a loss for what to do at this point having searched many different forums and posts about syntax and such.
The full stacktrace is as follows:
Exception in thread "main" org.sqlite.SQLiteException: [SQLITE_BUSY] The database file is locked (database is locked)
at org.sqlite.core.DB.newSQLException(DB.java:909)
at org.sqlite.core.DB.newSQLException(DB.java:921)
at org.sqlite.core.DB.execute(DB.java:822)
at org.sqlite.core.DB.executeUpdate(DB.java:863)
at org.sqlite.jdbc3.JDBC3PreparedStatement.executeUpdate(JDBC3PreparedStatement.java:99)
at SqliteDB.createUser(SqliteDB.kt:50)
at SqliteDBKt.main(SqliteDB.kt:122)
I don't believe the issue is with an open connection as the error seems to occur as soon as I try to execute the update to the User table. The insert seems to hit some sort of loop of some kind at the execution stage.
EDIT: Something else I noticed, is that when attempting to create a new user with a primary key (userID) that already exists, I am given a uniqueness error, suggesting the update is going thru and realizing the userID is already in the table; however, there is still the issue with the INSERT creating a new row in the table. I'm just not sure how to go about debugging that specific issue.
So this has been quite an issue for me for the past week or so and it looks like I have been able to figure out the issue.
I am aware that you have to make sure to close any connections to the database before opening a new one to avoid locks and any other similar issues. What I did not realize is that I have been using a program in IntelliJ called "DB Browser". This plugin creates a UI that much more easily allows you to access and change any aspect of the database you want without using actual SQL commands. What I didn't realize is this plugin takes up the only writeable connection the SQLite and JDBC allow to the database.
So, after deleting the connection to the database through the DB Browser plugin, all of my functions are working properly.

Teradata : Which dbc table contains the ACCOUNT field?

I need to find out what is my account . I looked at the following tables :
dbc.accounts
DBC.AccountInfoV
DBC.ProfileInfo
They have the accountname, which is not the same . WHere can I find my account ?
Thanks
Your currently active account can be retrieved using the built-in ACCOUNT function:
SELECT ACCOUNT;
Your default account is returned by:
SELECT DefaultAccount
FROM dbc.UsersV
WHERE UserName = USER;
And the list of all accounts your user might use, assigned either to the user directly or via the user's profile:
SELECT AccountName
FROM dbc.accountinfoVX
WHERE (PROFILE IS NULL AND USERNAME = USER)
OR (USERNAME = PROFILE)

SQLite update query is not updating table data with phonegap3.1

I am new user for SQLite. I am using phonegap3.1 foe android. I have an issue while updating user table. Below is the code that I am using:
var db = window.openDatabase("riazdb", "1.0", "Demo", 200000);
var userName = "user1";
db.transaction(function(tx) {
tx.executeSql('UPDATE user SET auto_login = "true" WHERE name = ?', [userName], userUpdateSuccess, userUpdateError);
}, userUpdateError);
function userUpdateSuccess(tx, results) {
console.log("affected rows : "+results.rowsAffected);
}
function userUpdateError(err) {
console.log("userUpdateError");
}
I am getting response as a success with results.rowsAffected = 1.
Can somebody tell me that what am I doing wrong.
Thanks
I had the exact same scenario.
Take a look in your onSuccess callback. If there is an unhanded exception thrown from your onSuccess handler, you will see the success happen, you will see rowsAffected == 1. However I suspect that the exception in the success handler causes phonegap to never WRITE the results to the table.
HTH

Cannot select a record in User Information (UserInfo). User ID: , . Dynamics Ax 2009

== UPDATED :) =========
! SEEMS LIKE ANOTHER 2100 LIMIT ! PLEASE HELP !
Here's some update of what we've found :
I've written a simple job :
server static void testEs(Args _args)
{
UserInfo t;
;
select t;
}
When I run it as admin, there's no problem. When I remove my admin privilege and run it again, I still got that error :
Cannot select a record in User Information (UserInfo). User ID: , .
For simple test, we deleted some users, passing from 2188 to 2074 users. The users deleted has been in the system for a while (a month ago). I redo the same test (running the above job when non-Admin) and now it works.
Any idea anyone ??????
== ORIGINAL MESSAGE ==================
Hi ! (Sorry for my bad english)
We encountered a problem when non-Admin users try to log in Ax in our production environment.
Actually, there is an infolog with these messages (the stack trace is appended to the message) :
== Infolog ========
Cannot select a record in User Information (UserInfo). User ID: , .
The SQL database has issued an error.
(S)\Classes\Info\checkStartupCompany_Server - line 8
(C)\Classes\Info\checkStartupCompany - line 4
(C)\Classes\Info\startup - line 49
Here's the sql statement with the bug :
SQL statement: SELECT TOP 1 A.COMPANY,A.ID,101090 FROM USERINFO A WHERE ((((ID IN (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,
[.. and goes on ..]
?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ))
== End Infolog ========
Here's the content of Info::checkStartupCompany_Server with the HERE comment where it does bug :
server static void checkStartupCompany_Server(str _curext, userId _curuseid)
{
UserInfo userInfo;
if (!hasMenuItemAccess(menuitemdisplaystr(SysDataAreaSelect), MenuItemType::Display) ||
!hasMenuItemAccess(menuitemdisplaystr(SysDataArea), MenuItemType::Display))
{
select firstonly Company from userInfo
where userInfo.Id == curuserid(); // <== HERE !!!!!!!!!!!!!!
if (userInfo.Company != curext())
{
appl.setDefaultCompany(userInfo.Company, false);
}
}
}
=============
In the code of Info::checkStartupCompany_Server, it makes sens that Admin users doesn't have that problem since the condition above is bypassed.
We have now doubts about the company settings.
Any help is appreciated :)
Thanks in advance :)
== END ORIGINAL MESSAGE ==================
Increase procedure call(RPC) on your sour AOS.
else Delete some users which were recently imported.
in my case this works.
I think you may have Record Level Security enabled on the UserInfo table.

Resources