Database Member
Posts : 318 Join date : 2012-03-04
| Subject: Can you expand an array of N to fill N functional arguments? Fri Jul 27, 2012 11:12 pm | |
| 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 hawkish: - 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. |
|
Database Member
Posts : 318 Join date : 2012-03-04
| Subject: Re: Can you expand an array of N to fill N functional arguments? Fri Jul 27, 2012 11:13 pm | |
| 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. |
|
Database Member
Posts : 318 Join date : 2012-03-04
| Subject: Re: Can you expand an array of N to fill N functional arguments? Fri Jul 27, 2012 11:13 pm | |
| ralph l mayo, thanks for reply code you pasted work fine |
|
Sponsored content
| Subject: Re: Can you expand an array of N to fill N functional arguments? | |
| |
|