Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder ralph l mayo's Avatar
    Join Date
    Nov 2005
    Posts
    951
    Thanks
    1
    Thanked 31 Times in 29 Posts

    Can you expand an array of N to fill N functional arguments?

    I've made this abstract class other classes can implement to make themselves storable in a MPTT database scheme without having knowledge of the left/right juggling. In the new entry part of class, I need to be able to insert an arbitrary length hash (@attrs) into the database (using DBI). I can generate the SQL for N values, but when it comes to executing it the SQL DBI's execute() method will not expand an array to fill the arguments it is expecting.

    I tried this first:
    Code:
    	cursor = @dbd.prepare(
    		"INSERT INTO #{ @table } (#{ @columns['left'] }, #{ @columns['right'] }, #{ @attrs.keys.join(', ') }) 
    			VALUES (?, ?#{ ', ?' * @attrs.length })")
    	
    		cursor.execute(l, l + 1, @attrs.values)
    But execute() fails for @attrs.length > 1

    This works, but it's very hackish:
    Code:
    	exec_attrs = @attrs.keys.collect { |k| "@attrs['#{ k }']" }
    	eval "cursor.execute(l, l + 1, #{ exec_attrs.join(', ') })"
    So, any better way to do it? Aside from rewriting execute() to handle arrays the way I want, which I may end up doing.

  • #2
    Regular Coder ralph l mayo's Avatar
    Join Date
    Nov 2005
    Posts
    951
    Thanks
    1
    Thanked 31 Times in 29 Posts
    I still don't have a general solution for this but there's a mechanism in DBI that fixes this instance:

    Instead of
    Code:
    cursor.execute(l, l + 1, @attrs.values)
    You can do
    Code:
    cursor.bind_param(1, l)
    cursor.bind_param(2, l + 1)
    @attrs.each_with_index { |at, idx|
        cursor.bind_param(idx + 3, at[1])
    }
    Much better.

  • #3
    New to the CF scene
    Join Date
    Nov 2007
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts
    ralph l mayo, thanks for reply
    code you pasted work fine


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •