Capture result output of send query in RSQLite - r

I would like to log the the number of rows changed when doing an update to a table in SQLite using RSQLite.
This:
dbSendQuery(db, "UPDATE FOO SET BAR = 1 WHERE BAZ = 0)
Returns an S4 object:
<SQLiteResult>
SQL UPDATE FOO SET BAR = 1 WHERE BAZ = 0
ROWS Fetched: 0 [Complete]
Changed: 11965
When I store the S4 object, I can call most of the content it seems (for example example_S3#sql provides the pure SQL code), but I can't get at the "Changed" bit (see above), which I'd like to log.
Any help is appreciated, limited SQL experience I'm afraid.

According to the doc you want the dbGetRowsAffected function
The number of rows affected
This function returns the number of rows that were added, deleted, or
updated by data modifying query. For a selection query, this function
returns 0.

Related

Julia Querying from SQLite

Following this tutorial https://www.youtube.com/watch?app=desktop&v=qUrtLJcehE0, I created a database called Movies. Within the database a table called movies was created and next an entry was also added,
using SQLite
db = SQLite.DB("Movies")
SQLite.execute(db,"CREATE TABLE IF NOT EXISTS movies(movie_id REAL,movie_name TEXT, location TEXT)")
SQLite.execute(db,"INSERT INTO movies (movie_id,movie_name,location) VALUES(1,'Avengers','USA')")
However now when I try to Query the entry as follows,
SQLite.Query(db, "SELECT * from movies")
I get the this error, Error: MethodError: no method matching SQLite.Query.(::SQLite.DB,::String).
Any Ideas what I am doing wrong?
I don't know SQL, but I think you want to use SQLite.execute again not SQLite.Query. SQLite.Query is a struct not a function, and it doesn't have any documentation. I don't think you are meant to call it externally. Further documentation is here.
Method error means you are calling something with the wrong arguments. The SQLite.Query struct expects all of the following arguments:
struct Query
stmt::Stmt
status::Base.RefValue{Cint}
names::Vector{Symbol}
types::Vector{Type}
lookup::Dict{Symbol, Int}
end
The SQLite.execute function expects arguments in one of these forms:
SQLite.execute(db::SQLite.DB, sql, [params])
SQLite.execute(stmt::SQLite.Stmt, [params])
By convention in Julia, functions are all lowercase and types are capitalized.
To load a table using SQLite package,
using SQLite
using DataFrames
# Make a connection
db = SQLite.DB("Movies")
# To find out all tables available in schema
tbls = SQLite.tables(db)
# To load a specific table (movies table from Movies.db)
q = "SELECT * FROM movies"
data = SQLite.DBInterface.execute(db,q)
# To get as a dataframe
df = DataFrames.DataFrame(data)

tsqlt testing an output parameter from a stored procedure

I have a stored procedure that I am trying test for the proper generation of an output parameter. I experimented with tsqlt.ExpectException, but that did not work. I instead am trying tsqlt.AssertEqualsTable.
CREATE TABLE #actual (msg NVARCHAR(MAX));
CREATE TABLE #expected (msg NVARCHAR(MAX));
INSERT #expected (msg) VALUES (N'Location w1005 has LPNs that were produced against a different production order than 1')
--EXEC tSQLt.ExpectException #ExpectedMessage = N'Location 1 has LPNs that were produced agains a different production order than orderNumber';
EXEC dbo.wms_whse_check_location
#command = #Command, #operLocationHasOtherLPN=#operLocationHasOtherLPN OUTPUT;
INSERT #actual (msg) VALUES (#operLocationHasOtherLPN)
EXEC tsqlt.AssertEqualsTable #Expected = '#expected', #actual = '#actual'
The test fails, and the output from tsqlt is:
Unexpected/missing resultset rows!
|m|msg |
+---+--------------------------------------------------------------------------------------+
|< |Location w1005 has LPNs that were produced against a different production order than 1|
|> |Location w1005 has LPNs that were produced against a different production order than l|
It may be hard to see in the above snip, but the < (expected) row is identical to the > (actual) row -- tsqlt finds a difference that in fact doesn't exist. I'm not choosing the correct method it seems.
Has anyone written tests to check ouput parameters? What is the appropriate method? Thanks
p.s. Apologies for the messy formatting. I'm not a regular poster.
tSQLt.AssertEqualsString is in fact the appropriate test. I don't know where I went wrong, but when I concatenated the appropriate expected message in code (as opposed to typing it out), then ran the test, it succeeded.
Use tSQLt.AssertEqualsString, as you found out already.
Also, your two strings are not identical. The one ends in “1”, the other one doesn’t.

Haskell SQLite3 query all

Would like to determine the size of a table (length) to avoid a user entering an incremental ID that already exists (Note: left all Haskell books to get my feet wet). Got a table with id, task, date_in, date_out and need to count the number id's. Using this function:
checkUniqueID = do
conn <- open "taglist.db"
len <- query conn "SELECT * FROM task;" (Only xxx) :: IO [id]
let showLength = length $ len
print showLength
close conn
return ()
However: omitting the 'Only' will result in ghci mentioning too few arguments, but I really cannot figure out what to put at xxx. Too bad all Haskell doc is so fragmented, since it is such a cool language.
Thanks guys!
I am not terribly familiar with these libraries. I check the docs
of Database.PostgreSQL.Simple
and found out that, if you don't have arguments to your query, you can use query_ and omit the argument tuple. The examples at the very beginning of the docs are quite helpful.
That being said, your approach looks wrong. You are pulling the whole table from the DB only to count the entries. This is a waste: you should instead use something like select count(*) from .. so that you query for the length only.
This might work: (again, I've never used that library)
[Only len] <- query_ conn "select count(*) from task" :: IO [Only Int]

Second dict refering to first dict doesn't register changes to first

dictOne = {'a':1, 'b':2}
dictTwo = {'aa':dictOne['a'], 'bb':dictOne['b']}
print(dictTwo['aa']
# returns 1
If I make a change to dictOne like:
dictOne['a'] = 2
print(dictOne['a'])
# returns 2
but the second dict that refers to the first still returns the original value.
print(dictTwo['aa'])
# returns 1
What is happening here? I'm sure this is somehow an inappropriate usage of dict but I need to resolve this in the immediate. Thanks.
You're extracting the value from the key 'a' inside dictOne with the below piece of code
dictTwo = {'aa':dictOne['a']}
You may find some value in reading the python FAQ on pass by assignment
Without knowing more about the problem, it's difficult to say exactly how you can solve this. If you need to create a mapping between different sets of keys, there's the option to do something like:
dictTwo = {'aa' : 'a', 'bb' : 'b'}
dictOne[dictTwo['aa']]
Although maybe what you're looking for is a multi key dict
The line here:
dictTwo = {'aa':dictOne['a'], 'bb':dictOne['b']}
Is equivalent to:
dictTwo = {'aa':1, 'bb':2}
Since dictOne['a'] and dictOne['b'] both return immutable values (integers), they are passed by copy, and not by reference. See How do I pass a variable by reference?
Had you done dictTwo = dictOne, updating dictOne would also update dictTwo, however they would have the same key values.

Simple function in lua: pick a random parameter passed into it

i would love to have functionality like this:
print(randomParameter(1,2,3))
-- prints 1 2 or 3... randomly picks a parameter
i have tried using the func(...) argument but i cant seem to use the table ARG when i pass multiple parameters. I tried this:
function hsv(...)
return arg[math.random(1,#arg)] -- also tried: return arg[math.random(#arg)]
end
print(hsv(5,32,7))
i have even tried putting the #arg into a variable using the rand function, also making a for loop with it sequentially adding a variable to count the table. still nothing works.
i remember doing this a while back, amd it looked different then this. can anyone Help with this? THANKS!
To elaborate a bit on #EgorSkriptunoff's answer (who needs to change his habit of providing answers in comments ;)): return (select(math.random(select('#',...)),...)).
... provides access to vararg parameter in the function
select('#', ...) returns the number of parameters passed in that vararg
math.random(select('#',...)) gives you a random number between 1 and the number of passed parameters
select(math.random(select('#',...)),...) gives you the element with the index specified by that random number from the passed parameters.
The other solution that is using arg = {...} gives you almost the same result with one subtle difference related to the number of arguments when nil is included as one of the parameters:
> function f(...) print(#{...}, select('#', ...)) end
> f(1,2,3)
3 3
> f(1,2,nil)
2 3
> f(1,2,nil,3)
2 4
As you can see select('#',...) produces more accurate results (this is running LuaJIT, but as far as I remember, Lua 5.1 produces similar results).
function randomNumber(...)
t = {...}
return t[math.random(1,#t)]
end
print(randomNumber(1, 5, 2, 9))
> 1 or 5 or 2 or 9

Resources