lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello,

This ground was covered, for example, by Edgar Toernig, back in 2007:

http://lua-users.org/lists/lua-l/2007-10/msg00189.html

Nonetheless I would like to sanity check my current concoction :)

Basically I would like to somewhat emulate the following construct, but in Lua:

[sqlite3 & cat used for illustration purpose only]

% sqlite3 -bail <<< 'select count( * ) as count from sqlite_master;'; echo $? | cat;
> 0
> 0

Of course, failures should be detected as well:

% sqlite3 -bail <<< 'select count( * ) as count from sqlite_mister;'; echo $? | cat;
> Error: near line 1: no such table: sqlite_mister
> 1

Here is the broadly equivalent Lua construct I’m aiming at:

lua - <<\EOF
local aCommand = 'sqlite3 -bail | cat'
local aHandle = assert( io.popen( aCommand, 'w' ) )

assert( aHandle:write( '.head on', '\n' ) )
assert( aHandle:write( 'select count( * ) as count from sqlite_master;', '\n' ) )
-- ... many other sql commands...
print( aHandle:close() )
EOF

> count
> 0
> true	exit	0

Looks reasonable enough, but with one gotcha: it never raises any exception when confronted with invalid commands:

lua - <<\EOF
local aCommand = 'sqlite3 -bail | cat'
local aHandle = assert( io.popen( aCommand, 'w' ) )

assert( aHandle:write( '.head on', '\n' ) )
assert( aHandle:write( 'select count( * ) as count from sqlite_mister;', '\n' ) ) -- invalid table name
print( aHandle:close() )
EOF

> Error: near line 2: no such table: sqlite_mister
> true	exit	0

What would be a reasonable way to capture the exit code of the initial command (sqlite3) as opposed to the piped one (cat)?

Is using PIPESTATUS reasonable enough?


lua - <<\EOF
local aCommand = 'sqlite3 -bail | cat; exit ${PIPESTATUS[0]};'
local aHandle = assert( io.popen( aCommand, 'w' ) )

assert( aHandle:write( '.head on', '\n' ) )
assert( aHandle:write( 'select count( * ) as count from sqlite_mister;', '\n' ) )
print( aHandle:close() )
EOF

> Error: near line 2: no such table: sqlite_mister
> nil	exit	1

Seems to have the expected effect. 

Thoughts? Suggestions?

Thanks in advance.