A typical SQL Query in Erlang and Ejabberd - erlang

I want some help in writing a typical SQL query in Erlang. I just want to prevent logging the offline message based on this query.
Want to put this query at start of this function.
store_offline_msg(Host, {User, _Server}, Msgs, Len, MaxOfflineMsgs, odbc) ->
Count = if MaxOfflineMsgs =/= infinity ->
Len + count_offline_messages(User, Host);
true -> 0
end,
if Count > MaxOfflineMsgs -> discard_warn_sender(Msgs);
Mysql Table
ID | user | touser | starttime | end
586 | my_gmail.com | touser_gmail.com | 2014-10-29 14:03:16 | 60
Query I need is to check:
if 'user' and 'touser' have a record in this table, and current time comes in between starttime and startime + end (60 seconds)
Please help me in this, I appreciate it.

Here is how I implemented it and solved my problem.
Check = case catch ejabberd_odbc:sql_query(
LServer,
["select id from archive_disable_user"
" where ( ( user ='", To, "' "
" and tuser='", From , "' ) "
" or ( user ='", From, "' "
" and tuser='", To , "' ) )"
" and ( ( UNIX_TIMESTAMP(start) + end ) > UNIX_TIMESTAMP()); "]) of
{selected, ["id"], Rs} ->
Rcheck = len(Rs),
if
Rcheck == 0 ->
false;
true->
true
end;
_-> false
end,
Check.

Related

Simple interpreter incorrectly parses file

Yesterday I've wrote interpreter for my new programming language, and I've put it on Github. Before this i made some simple tests and it seemed to work but now when i wanted to write some examples - it didn't work at all! I was really surprised, how did I get that output. For simple programs like this:
string Hello World!
locate 0
puts
It worked really well, displaying output 'Hello World!'. More complicated program looked like this:
ADD 49
PUTCH
SUB 1
PUTCH
MUL 2
ADD 1
PUTCH
SUB 1
DIV 2
PUTCH
LOCATE 2
PUTD
LOCATE 0
SETV 10
PUTCH
SETV 0
LOCATE 0
STRING Hello World
LOCATE 0
PUTS
SETV 10
UNTILZERO
{
SUB 1
}
IFCC 10 == 10 {
LOCATE 0
SETV 0
STRING Ok!
LOCATE 0
PUTS
}
To understand this you need just some knowledge of Lua, C and Assembly.
How to run code above: ./lua start.lua test.txt -gencode
Output:
}UTSTE 0k! 10 {rld
local tape = {}
local pointer = 0
}UTSTE 0k! 10 {rldpe[pointer] + 49
(I don't understand any part of this invaild output)
So actually my code looks like this:
--[[
____ _ __ _ _ _
| _ \ (_) / _| | | _| || |_
| |_) |_ __ __ _ _ _ __ | |_ _ _ ___| | _|_ __ _|
| _ <| '__/ _` | | '_ \| _| | | |/ __| |/ /_| || |_
| |_) | | | (_| | | | | | | | |_| | (__| <|_ __ _|
|____/|_| \__,_|_|_| |_|_| \__,_|\___|_|\_\ |_||_|
Brainfuck# v 1.0. Copyright (C) by Krzysztof Szewczyk.
For more information check CONTRIB.MD and LICENSE.
Code is licensed under GPLv3.
--]]
output = "local tape = {}\nlocal pointer = 0\n" --We will use Lua 'eval'-like function.
brackets = 0
-- Parse command with parameters 'params', and parameter number
-- 'paramno'.
function parse(command,params,paramno)
if command == nil or params == nil or paramno == nil then return end
local cmd = string.upper(command)
if cmd == ";" then end
if cmd == "ADD" then
local amount = params[1]
output = output .. "tape[pointer] = tape[pointer] + " .. amount .. "\n"
end
if cmd == "SUB" then
local amount = params[1]
output = output .. "tape[pointer] = tape[pointer] - " .. amount .. "\n"
end
if cmd == "MUL" then
local amount = params[1]
output = output .. "tape[pointer] = tape[pointer] * " .. amount .. "\n"
end
if cmd == "DIV" then
local amount = params[1]
if amount == 0 then
print("[JIT] - Divide-by-zero error.")
end
output = output .. "tape[pointer] = tape[pointer] / " .. amount .. "\n"
end
if cmd == "ADDP" then
local amount = params[1]
output = output .. "pointer = pointer + " .. amount .. "\n"
end
if cmd == "SUBP" then
local amount = params[1]
output = output .. "pointer = pointer - " .. amount .. "\n"
end
if cmd == "MULP" then
local amount = params[1]
output = output .. "pointer = pointer * " .. amount .. "\n"
end
if cmd == "DIVP" then
local amount = params[1]
if amount == 0 then
print("[JIT] - Divide-by-zero error.")
end
output = output .. "pointer = pointer / " .. amount .. "\n"
end
if cmd == "LOCATE" then
local pos = params[1]
output = output .. "pointer = " .. pos .. "\n"
end
if cmd == "SETV" then
local val = params[1]
output = output .. "tape[pointer] = " .. val .. "\n"
end
if cmd == "STRING" then
local str = params[1]
for i = 1, #str do
local c = str:sub(i,i)
output = output .. "tape[pointer] = string.byte(\"" .. c .. "\")\n"
output = output .. "pointer = pointer + 1\n"
end
output = output .. "tape[pointer] = 0\n" --Remember to add null terminator (this can overwrite some of
--your crap stored in tape, so please have this in mind).
output = output .. "pointer = pointer + 1\n"
end
if cmd == "PUTCH" then
--Simply, no arguments
output = output .. "io.write(string.char(tape[pointer]))\n"
end
if cmd == "PUTD" then
--Simply, no arguments ^
output = output .. "io.write(tape[pointer])\n" --Just print integer (as integer, not character, for character see |)
end
if cmd == "PUTS" then
output = output .. "lastpntr=0\nwhile true do\nif tape[pointer] == 0 then break end\nio.write(string.char(tape[pointer]))\npointer = pointer + 1\nend\npointer=lastpntr\n" --I belive it's too complicated
--But it works.
end
if cmd == "GETCH" then
output = output .. "tape[pointer] = io.read()\n" --HACK: Any raw input is not possible in multiplatform way.
end
if cmd == "UNTILZERO" then
output = output .. "while tape[pointer]\n"
end
if cmd == "{" then
output = output .. "do\n"
brackets = brackets + 1;
end
if cmd == "}" then
output = output .. "end\n"
brackets = brackets - 1;
end
if cmd == "IUNTIL" then
local type = params[1]
local value = params[2]
output = output .. "while tape[pointer] " .. type .. value .. "\n"
brackets = brackets - 1;
end
if cmd == "TUNTIL" then
local type = params[1]
local value = params[2]
output = output .. "while tape[pointer] " .. type .. "tape[" .. value .. "]" .. "\n"
brackets = brackets - 1;
end
if cmd == "IFCC" then
local val1 = params[1];
local comp = params[2];
local val2 = params[3];
if params[4] == "{" then
output = output .. "if " .. val1 .. comp .. val2 .. " then\n"
else
print("[JIT]: IFCC needs starting bracket at 4th argument. Please pass it and don't forget to close it.")
end
end
if cmd == "IFCT" then
local val1 = params[1];
local comp = params[2];
local val2 = params[3];
if params[4] == "{" then
output = output .. "if " .. val1 .. comp .. "tape[" .. val2 .. "] then\n"
else
print("[JIT]: IFCC needs starting bracket at 4th argument. Please pass it and don't forget to close it.")
end
end
if cmd == "IFTT" then
local val1 = params[1];
local comp = params[2];
local val2 = params[3];
if params[4] == "{" then
output = output .. "if tape[" .. val1 .. "]" .. comp .. "tape[" .. val2 .. "] then\n"
else
print("[JIT]: IFCC needs starting bracket at 4th argument. Please pass it and don't forget to close it.")
end
end
end
-- Function to split strings. Any questions?
function string:split( inSplitPattern, outResults )
if not outResults then
outResults = { }
end
local theStart = 1
local theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart )
while theSplitStart do
table.insert( outResults, string.sub( self, theStart, theSplitStart-1 ) )
theStart = theSplitEnd + 1
theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart )
end
table.insert( outResults, string.sub( self, theStart ) )
return outResults
end
-- I create new function to ensure that variables
-- won't escape local context.
function main(filename,gencodeswitch)
local input = io.open(filename, "r")
if input then
--No error found while opening file
while true do
--First, read line.
local line = input:read()
--Now, let's check is it nil.
--If so, we can break out of this loop.
if line == nil then break end
--Else, we need to parse this instruction.
--So break it into main command and it's params.
local space = string.find(line, " ") --Find first space occurence (to divide
--command from it's arguments).
local params = string.sub(line, space+1) -- To get params just split string.
local command = string.sub(line, 0, space-1) -- To get command without trailing space.
--Actually, this space will get removed.
local paramTable = params:split(",")
local paramAmount = 0
-- HACK: Looks like ineffective solution, but who cares?
for i = 1, #paramTable do
paramAmount = paramAmount + 1;
end
print ("line:" .. line)
parse(command,paramTable,paramAmount)
end
--Done parsing. Generate code
if brackets ~= 0 then print("[JIT] Unbalanced brackets.") os.exit() end
if gencodeswitch == "-gencode" then print(output) end
--loadstring(output)()
else
--Oops, an error occured. Couldn't open file.
print("[JIT]: Please pass vaild filename.")
os.exit() --Bye, see ya later
end
end
if arg[1] == nil then
--User didn't pass any arguments.
print("Brainfuck# v 1.0")
print("Ussage:")
print(".\lua start.lua <input> [-print]")
print("Where:")
print(".\lua - lua executable")
print("start.lua - main module name");
print("<input> - input filename (non-optional!)")
print("[-print] - Optional, print source before execution.")
os.exit();
else
--User passed an argument
main(arg[1],arg[2])
end
I can't find any errors but there must be a mistake.
If you want to see repo, here it is, but it doesn't contain
anything except license, readme, build and test scripts.
I've put some comments to make understanding this broken code
and trying to fixing it easier.
Can anyone point me out where have I made a mistake?
I took the liberty to completely revise your code as I saw too many problems with it. (It didn't even compile as you posted it.) I guess you're new to programming. Anyway, there is still much more work needed but I'll leave the rest of it for you. However, it does seem to work now for your example input at least.
I saved your example program as sample.bf and with the command
brainfuck#.lua sample.bf -gencode | lua got Hello World! as output. Which is correct, as far as I can tell.
--[[
____ _ __ _ _ _
| _ \ (_) / _| | | _| || |_
| |_) |_ __ __ _ _ _ __ | |_ _ _ ___| | _|_ __ _|
| _ <| '__/ _` | | '_ \| _| | | |/ __| |/ /_| || |_
| |_) | | | (_| | | | | | | | |_| | (__| <|_ __ _|
|____/|_| \__,_|_|_| |_|_| \__,_|\___|_|\_\ |_||_|
Brainfuck# v 1.0. Copyright (C) by Krzysztof Szewczyk.
For more information check CONTRIB.MD and LICENSE.
Code is licensed under GPLv3.
--]]
output = [[
local tape = {}
local pointer = 0
]] --We will use Lua 'eval'-like function.
brackets = 0
-- Parse command with parameters 'params', and parameter number 'paramno'.
function parse(cmd,params,paramno)
if cmd == nil or params == nil or paramno == nil then return end
cmd = cmd:upper()
local amount
if cmd == ";" then
elseif cmd == "ADD" then
amount = params[1]
output = output .. "tape[pointer] = tape[pointer] + " .. amount .. "\n"
elseif cmd == "SUB" then
amount = params[1]
output = output .. "tape[pointer] = tape[pointer] - " .. amount .. "\n"
elseif cmd == "MUL" then
amount = params[1]
output = output .. "tape[pointer] = tape[pointer] * " .. amount .. "\n"
elseif cmd == "DIV" then
amount = params[1]
if amount == 0 then
print("[JIT] - Divide-by-zero error.")
end
output = output .. "tape[pointer] = tape[pointer] / " .. amount .. "\n"
elseif cmd == "ADDP" then
amount = params[1]
output = output .. "pointer = pointer + " .. amount .. "\n"
elseif cmd == "SUBP" then
amount = params[1]
output = output .. "pointer = pointer - " .. amount .. "\n"
elseif cmd == "MULP" then
amount = params[1]
output = output .. "pointer = pointer * " .. amount .. "\n"
elseif cmd == "DIVP" then
amount = params[1]
if amount == 0 then
print("[JIT] - Divide-by-zero error.")
end
output = output .. "pointer = pointer / " .. amount .. "\n"
elseif cmd == "LOCATE" then
local pos = params[1]
output = output .. "pointer = " .. pos .. "\n"
elseif cmd == "SETV" then
local val = params[1]
output = output .. "tape[pointer] = " .. val .. "\n"
elseif cmd == "STRING" then
local s = params[1]
for i = 1, #s do
local c = s:sub(i,i)
output = output .. "tape[pointer] = string.byte(\"" .. c .. "\")\n"
output = output .. "pointer = pointer + 1\n"
end
output = output .. "tape[pointer] = 0\n"
--Remember to add null terminator (this can overwrite some of your crap
--stored on tape, so please have this in mind).
output = output .. "pointer = pointer + 1\n"
elseif cmd == "PUTCH" then --Simply, no arguments
output = output .. "io.write(string.char(tape[pointer]))\n"
elseif cmd == "PUTD" then --Simply, no arguments ^
output = output .. "io.write(tape[pointer])\n" --Just print integer (as integer, not character, for character see |)
elseif cmd == "PUTS" then
output = output .. [[
lastpntr=0
while true do
if tape[pointer] == 0 then break end
io.write(string.char(tape[pointer]))
pointer = pointer + 1
end
pointer=lastpntr
]] --I believe it's too complicated but it works.
elseif cmd == "GETCH" then
output = output .. "tape[pointer] = io.read()\n" --HACK: Any raw input is not possible in multiplatform way.
elseif cmd == "UNTILZERO" then
output = output .. "while tape[pointer]\n"
elseif cmd == "{" then
output = output .. "do\n"
brackets = brackets + 1
elseif cmd == "}" then
output = output .. "end\n"
brackets = brackets - 1
elseif cmd == "IUNTIL" then
local type = params[1]
local value = params[2]
output = output .. "while tape[pointer] " .. type .. value .. "\n"
brackets = brackets - 1
elseif cmd == "TUNTIL" then
local type = params[1]
local value = params[2]
output = output .. "while tape[pointer] " .. type .. "tape[" .. value .. "]" .. "\n"
brackets = brackets - 1
elseif cmd == "IFCC" then
local val1 = params[1]
local comp = params[2]
local val2 = params[3]
if params[4] == "{" then
output = output .. "if " .. val1 .. comp .. val2 .. " then\n"
else
print("[JIT]: IFCC needs starting bracket at 4th argument. Please pass it and don't forget to close it.")
end
elseif cmd == "IFCT" then
local val1 = params[1]
local comp = params[2]
local val2 = params[3]
if params[4] == "{" then
output = output .. "if " .. val1 .. comp .. "tape[" .. val2 .. "] then\n"
else
print("[JIT]: IFCC needs starting bracket at 4th argument. Please pass it and don't forget to close it.")
end
elseif cmd == "IFTT" then
local val1 = params[1]
local comp = params[2]
local val2 = params[3]
if params[4] == "{" then
output = output .. "if tape[" .. val1 .. "]" .. comp .. "tape[" .. val2 .. "] then\n"
else
print("[JIT]: IFCC needs starting bracket at 4th argument. Please pass it and don't forget to close it.")
end
end
end
-- Function to split strings. Any questions?
function string:split( inSplitPattern, outResults )
outResults = outResults or {}
local theStart = 1
local theSplitStart, theSplitEnd = self:find(inSplitPattern, theStart)
while theSplitStart do
table.insert( outResults, self:sub(theStart, theSplitStart-1) )
theStart = theSplitEnd + 1
theSplitStart, theSplitEnd = self:find(inSplitPattern, theStart)
end
table.insert( outResults, self:sub(theStart) )
return outResults
end
-- I create new function to ensure that variables won't escape local context.
function main(filename,gencodeswitch)
local file = io.open(filename, "r")
if file == nil then
--Oops, an error occured. Couldn't open file.
print("[JIT]: Please pass valid filename.")
os.exit() --Bye, see ya later
return
end
--No error found while opening file
local space,params,command,paramTable,paramAmount
for line in file:lines() do
--We need to parse this instruction.
--So break it into main command and it's params.
space = (line..' '):find(" ") --Find first space occurence (to divide command from it's arguments).
params = line:sub(space+1) -- To get params just split string.
command = line:sub(1, space-1) -- To get command without trailing space.
--Actually, this space will get removed.
paramTable = params:split(',')
-- HACK: Looks like ineffective solution, but who cares?
--for i = 1, #paramTable do paramAmount = paramAmount + 1 end
paramAmount = #paramTable
print ('--' .. line)
parse(command,paramTable,paramAmount)
end
file:close()
--Done parsing. Generate code
if brackets ~= 0 then print("[JIT] Unbalanced brackets.") os.exit() end
if gencodeswitch == "-gencode" then print(output) end
--loadstring(output)()
end
if arg[1] == nil then
--User didn't pass any arguments.
print [[
Brainfuck# v 1.0
Usage:
.\lua start.lua <input> [-print]
Where:
.\lua - lua executable
start.lua - main module name
<input> - input filename (non-optional!)
[-print] - Optional, print source before execution.]]
os.exit()
else
--User passed an argument
main(arg[1],arg[2])
end

Neo4j Cypher : replace multiple characters

i need to replace multiple characters by single character
RETURN LOWER(REPLACE("ranchod-das-chanchad-240190---Funshuk--Wangdu",'--', '-'))
is there any regex to do this
for neo4j 2.2.2
There's no function similar to REPLACE taking a regex as a parameter.
Since you're using Neo4j 2.2, you can't implement it as a procedure either.
The only way to do it is by splitting and joining (using a combination of reduce and substring):
RETURN substring(reduce(s = '', e IN filter(e IN split('ranchod-das-chanchad-240190---Funshuk--Wangdu', '-') WHERE e <> '') | s + '-' + e), 1);
It can be easier to read if you decompose it:
WITH split('ranchod-das-chanchad-240190---Funshuk--Wangdu', '-') AS elems
WITH filter(e IN elems WHERE e <> '') AS elems
RETURN substring(reduce(s = '', e IN elems | s + '-' + e), 1);

Can I create a gmatch pattern that returns a variadic number of values?

I need to iterate over some pairs of strings in a program that I am writing. Instead of putting the string pairs in a big table-of-tables, I am putting them all in a single string, because I think the end result is easier to read:
function two_column_data(data)
return data:gmatch('%s*([^%s]+)%s+([^%s]+)%s*\n')
end
for a, b in two_column_data [[
Hello world
Olá hugomg
]] do
print( a .. ", " .. b .. "!")
end
The output is what you would expect:
Hello, world!
Olá, hugomg!
However, as the name indicates, the two_column_data function only works if there are two exactly columns of data. How can I make it so it works on any number of columns?
for x in any_column_data [[
qwe
asd
]] do
print(x)
end
for x,y,z in any_column_data [[
qwe rty uio
asd dfg hjk
]] do
print(x,y,z)
end
I'm OK with using lpeg for this task if its necessary.
function any_column_data(data)
local f = data:gmatch'%S[^\r\n]+'
return
function()
local line = f()
if line then
local row, ctr = line:gsub('%s*(%S+)','%1 ')
return row:match(('(.-) '):rep(ctr))
end
end
end
Here is an lpeg re version
function re_column_data(subj)
local t, i = re.compile([[
record <- {| ({| [ %t]* field ([ %t]+ field)* |} (%nl / !.))* |}
field <- escaped / nonescaped
nonescaped <- { [^ %t"%nl]+ }
escaped <- '"' {~ ([^"] / '""' -> '"')* ~} '"']], { t = '\t' }):match(subj)
return function()
local ret
i, ret = next(t, i)
if i then
return unpack(ret)
end
end
end
It basicly is a redo of the CSV sample and supports quoted fields for some nice use-cases: values with spaces, empty values (""), multi-line values, etc.
for a, b, c in re_column_data([[
Hello world "test
test"
Olá "hug omg"
""]].."\tempty a") do
print( a .. ", " .. b .. "! " .. (c or ''))
end
local function any_column_data( str )
local pos = 0
return function()
local _, to, line = str:find("([^\n]+)\n", pos)
if line then
pos = to
local words = {}
line:gsub("[^%s]+", function( word )
table.insert(words, word)
end)
return table.unpack(words)
end
end
end
Outer loop returns lines, and inner loop returns words in line.
s = [[
qwe rty uio
asd dfg hjk
]]
for s in s:gmatch('(.-)\n') do
for s in s:gmatch('%w+') do
io.write(s,' ')
end
io.write('\n')
end

F# less than operator in pattern matching

For some reason the less than operator in this pattern match will not work. It's the only error I have and it's driving me insane.
I'm probably missing something really obvious but all help is appreciated.
let CheckAccount account =
match account with
| {Balance < 10.00} -> Console.WriteLine("Balance is Low")
| {Balance >= 10.00 and <= 100.00} -> Console.WriteLine("Balance is OK")
| {Balance > 100.00} -> Console.WriteLine("Balance is High")
This is the type:
type Account = {AccountNumber:string
mutable Balance:float}
member this.Withdraw(amnt:float) =
if amnt > this.Balance then
Console.WriteLine("Unable to withdraw. The Amount you wish to withdraw is greater than your current balance.")
else
this.Balance <- this.Balance - amnt
Console.WriteLine("You have withdrawn £" + amnt.ToString() + ". Your balance is now: £" + this.Balance.ToString())
member this.Deposit(amnt:float) =
this.Balance <- this.Balance + amnt
Console.WriteLine("£" + amnt.ToString() + " Deposited. Your new Balance is: £" + this.Balance.ToString())
member this.Print =
Console.WriteLine("Account Number: " + this.AccountNumber)
Console.WriteLine("Balance: £" + this.Balance.ToString())
You can use pattern matching to extract the balance value, bind it to a new name and then compare the values using the when clause:
let CheckAccount account =
match account with
| {Balance = b} when b < 10.00 -> Console.WriteLine("Balance is Low")
| {Balance = b} when b >= 10.00 && b <= 100.00 -> Console.WriteLine("Balance is OK")
| {Balance = b} when b > 100.00 -> Console.WriteLine("Balance is High")
I would say that in this case, you are not actually getting much from using pattern matching. If you wrote the same code using if, then it would probably look nicer.
You can use a bit fancier approach and define active patterns that let you compare values:
let (|LessThan|_|) k value = if value < k then Some() else None
let (|MoreThan|_|) k value = if value > k then Some() else None
Then you can use those instead:
let CheckAccount account =
match account with
| {Balance = LessThan 10.0} -> Console.WriteLine("Balance is Low")
| {Balance = LessThan 100.0 & MoreThan 10.0 } -> Console.WriteLine("Balance is OK")
This is actually fairly interesting - because you can use the & construct to combine multiple active patterns as in LessThan 100.0 & MoreThan 10.0.

How to use parameter from Expr usage

let useConnection expr =
let Expr(conn : MySqlConnection) =
try
try
conn.Open()
with
| :? MySqlException as ex
-> printfn "Exception! %s" ex.Message
expr(conn)
finally
try
conn.Close() |> ignore
with
| :? MySqlException as ex
-> printfn "Exception! %s" ex.Message
using (new MySqlConnection(ConnectionString =
"server = " + MySQLServer + ";
uid = " + MySQLUID + ";
pwd = " + MySQLPW + ";
database = " + MySQLDB + ";
Charset=utf8;")) Expr
member x.reportToDB (msg:string) =
useConnection // <--- SO HERE I WANT TO KNOW WHAT IS conn
(let cmd = new MySqlCommand(Connection = conn)
cmd.CommandText <- ("insert into "+MySQLTable+"(system,dt,logMessage);")
ignore <| cmd.Parameters.AddWithValue("?system", Net.Dns.GetHostName())
ignore <| cmd.Parameters.AddWithValue("?dt", DateTime.Now.ToString() )
ignore <| cmd.Parameters.AddWithValue("?logMessage", msg )
try
try
cmd.ExecuteNonQuery() |> ignore
with
| :? MySqlException as ex when ex.Message.Contains("Duplicate entry")
-> printfn "MySQL Duplicate entry Exception: discarding the data set! %s" ex.Message
printfn ""
| :? MySqlException as ex
-> printfn "MySQL Exception, requeing data set and trying again later! %s" ex.Message
reraise()
with
| :? MySqlException as ex
-> printfn "Exception! %s" ex.Message)
It's hard to explain but I want to use delegate conn from useConnection to x.reportToDB , how can I do it ?
thank you.
#Tim Robinson , yes I don't know about conn there and that is a problem I want to solve,
why you think that lambda is bad idea here ?
useConnection appears to want a function that takes a MySqlConnection. It supplies this function with the connection object that you want.
The fix is:
useConnection (fun conn (* here's your connection *) ->
let cmd = new MySqlCommand(Connection = conn)
// etc.
Edit: It's maybe clearer with type annotations added to the useConnection function:
let useConnection (expr : MySqlConnection -> 'a) : 'a =
let Expr(conn : MySqlConnection) : 'a =
// etc.

Resources