Connect to SQL Azure from Ruby Applications

Connect to SQL Azure from Ruby Applications

Click here to change the language (ja-JP).  

This article discusses the methods of connecting to SQL Azure from the Ruby language. While this article discusses several gems that can be used to connect to SQL Azure, it is by no means a comprehensive listing of all gems that provide this functionality.

NOTE: The procedures listed in this article may not work on all operating systems due to availability of ODBC drivers, differences in compilation process, etc. Currently this article contains information based on the Windows 7 operating system and the Windows Azure web or worker role hosting environment.


 

Initial Preparation

This article assumes that you are familiar with the Ruby language. It also assumes that you have the following:
  • Ruby 1.8.7, or 1.9.2
  • Windows Azure Platform subscription
  • SQL Azure database
    • Firewall settings that allow connectivity from your client IP address
NOTE: For more information on Ruby, visit http://www.ruby-lang.org/. For more information on the Windows Azure Platform, specifically for getting started with SQL Azure, see http://social.technet.microsoft.com/wiki/contents/articles/getting-started-with-the-sql-azure-database.aspx.

 

Ruby Database Connectivity

For connectivity to SQL Azure, we will be using the Ruby ODBC, TinyTDS, and Ruby OData gems. While there are other database connectivity methods available for the Ruby language, not all provide connectivity to SQL Azure.

All three gems can be installed through the gem command (http://docs.rubygems.org/read/book/2) by issuing the following commands:

gem install ruby-odbc
gem install tiny_tds
gem install ruby_odata
NOTE: Don’t install the tiny_tds gem using this command line format, as it will not be capable of connecting to SQL Azure. For more details on how to install this package with support for SQL Azure, see Using TinyTDS.

 

Using Ruby ODBC

Ruby ODBC provides access to ODBC data sources, including SQL Azure. This gem relies on your systems ODBC drivers for connectivity, so you must first ensure you have a working ODBC connection to your SQL Azure database. Perform the following steps to configure and test an ODBC connection:

To Configure ODBC on Windows 7

  1. From the start menu, enter ‘ODBC’ in the Search field. This should return a Data Sources (ODBC) program; select this entry.
  2. In the Data Sources program, select the User DSN tab, and then click Add.
  3. Select SQL Server Native Client 10.0, and then click Finish.
  4. Enter a name for this DSN, enter the fully qualified DNS name for your SQL Azure database, and then click Next.
  5. Select ‘With SQL Server authentication’ and enter the login ID and password you created when your database was provisioned. The username must be entered in the following format: ‘username@servername.database.windows.net’. When finished, click Next.
  6. Select ‘Change the default database to’ and then select a database other than master. When finished, click Next.
  7. Check ‘Use strong encryption for data’ to ensure that data passed between your client and SQL Azure is encrypted. When finished, click Finish.
  8. Click Test Data Source to ensure that you can connect.

To Connect to SQL Azure using Ruby ODBC

The following code is an example of using Ruby ODBC to connect to a SQL Azure database specified by a DSN named ‘azure’, perform a select against the ‘names’ table, and return the value of the ‘fname’ field.

require 'odbc'

sql='select * from [names]'
datasource='azure'
username='user@servername.database.windows.net'
password='password'

ODBC.connect(datasource,username,password) do |dbc|
results = dbc.run(sql)
results.fetch_hash do |row|
puts row['fname']
end
end

Active Record can also use Ruby ODBC to connect to a SQL Azure database. The following is an example database.yml for using an ODBC connection with Active Record.

development:
adapter: sqlserver
mode: ODBC
dsn: Driver={SQL Server};Server=servername.database.windows.net;Uid=user@servername.database.windows.net;Pwd=password;Database=databasename
NOTE: user, password, databasename and servername in the above examples must be replaced with valid values for your SQL Azure database.
NOTE: All tables in SQL Azure require a clustered index. If you receive an error stating that tables without a clustered index are not supported, add a :primary_key field. For more information, see Inside SQL Azure.
NOTE: The [schema_migrations] table will need a clustered index, and will return an error when you first attempt a migration (rake db:migrate). You can run the following command against your SQL Azure database to create a clustered index for this table after receiving this error:
CREATE CLUSTERED INDEX [idx_schema_migrations_version] ON [schema_migrations] ([version])

After creating the clustered index, rerun the migration and it should succeed.

 

Using TinyTDS

TinyTDS does not rely on ODBC to connect to SQL Azure; instead it directly uses the FreeTDS library. While TinyTDS can be installed using the gem install command, the version that is installed by default does not currently support connectivity to SQL Azure (it will work fine for SQL Server.) In order to communicate with SQL Azure, TinyTDS requires a version of FreeTDS that has been compiled with OpenSSL support. While providing a version of this via gem install is on the TODO list (https://github.com/rails-sqlserver/tiny_tds,) you can currently compile your own version of FreeTDS to enable SQL Azure connectivity.

NOTE: While the following steps worked for me, I can make no guarantees that they will work in your specific environment. If you have a better process, please help improve this article by sharing it.

 

To Build FreeTDS on Windows 7

Environment:

To build FreeTDS with OpenSSL support

  1. After installing Ruby, follow the DevKit installation and test steps at https://github.com/oneclick/rubyinstaller/wiki/Development-Kit.
  2. Download a current build of FreeTDS from FreeTDS.org. I used freetds-0.91rc.
  3. Download and install a Win32 version of OpenSSL and LibIconv. I used the GnuWin32 binary distribution that includes the libraries and header files, however other distributions may also work. Alternatively you may wish to download the source and build your own versions.
  4. Install or compile OpenSSL and LibIconv on your system, and then extract the FreeTDS source. To extract the FreeTDS package, you will need a utility that understands the .tgz format, such as 7Zip.
  5. In the directory where you have unzipped FreeTDS, find the ‘Configure’ file and edit it. NOTE: Notepad will not correctly recognize the linefeeds at the end of each line, so you may want to use a utility such as Notepad++ so that the file is more readable while editing it.
    Search for –lssl –lcrypto. These should occur on a line similar to the following:
    NETWORK_LIBS="$NETWORK_LIBS –lssl –lcrypto"
    For my environment, I had to change this line to
    NETWORK_LIBS="$NETWORK_LIBS –lssl32 –leay32 –lwsock32 –lgdi32"
    in order to successfully compile the project.
  6. From the DevKit folder, launch msys.bat. This will launch an sh.exe command window.
  7. Change directories to the location where you extracted the FreeTDS source. Note that while cd d: may work, the actual path reflected by this shell is a UNIX style path of /d. When specifying directories for the ./configure command later, I recommend specifying the paths using the /driveletter/folder format.
  8. From the FreeTDS source directory, run the following command:
    ./configure –prefix=<path to install FreeTDS to> —with-libiconv-prefix=<path to iconv> —with-openssl=<path to ssl>
    For example, if libiconv was installed to c:\libiconv and OpenSSL was installeld to c:\OpenSSL, the command would be
    ./configure –prefix=/c/freetds –with-libiconv-prefix=/c/libiconv –with-openssl=/c/openssl
  9. After the configuration process completes, run the following command: make
  10. Once the make process completes, run make install. This should copy the FreeTDS libraries to the directory specified by –prefix= during configuration.
  11. Add the <freetds install directory>\bin folder to the system path environment. This will allow the system to find the FreeTDS dll’s. NOTE: you must also add the OpenSSL\bin folder to the system path.

To build tiny_tds using the local FreeTDS library

From a command prompt, type the following:
gem install tiny_tds -platform=ruby -- --with-freetds-dir=<FreeTDS installation folder>
NOTE: If you receive an error about a duplicate definition of DBBIGINT, open <FreeTDS install folder\include\sybdb.h and search for the following line:
typedef tds_sysdep_int64_type DBBIGINT;
Place // at the beginning of the line to comment out this statement, and then run the gem install command again.

To connect to SQL Azure using TinyTDS

The following code is an example of connecting to SQL Azure using the tiny_tds gem:

require 'tiny_tds'

client=TinyTds::Client.new(:username=>’user’, :password=> ‘password’, :dataserver=>’servername.database.windows.net', :port=>1433, :database=>’databasename’, :azure=>true)
results=client.execute("select * from [names]")
results.each do |row|
puts row
end
NOTE: If you receive an error when stating that it cannot load ssleay32.dll when you run the above code, make a copy of the ssl32.dll file in the OpenSSL/bin folder and name the copy ssleay32.dll.

Tiny_tds can also be used with ActiveRecord. The following is an example database.yml for using a dblib connection to SQL Azure using the tiny_tds gem.

development:
adapter: sqlserver
mode: dblib
dataserver: 'servername.database.windows.net'
database: databasename
username: user
password: password
timeout: 5000
azure: true
NOTE: All tables in SQL Azure require a clustered index. If you receive an error stating that tables without a clustered index are not supported, add a :primary_key field.
NOTE: The [schema_migrations] table will need a clustered index, and will return an error when you first attempt a migration (rake db:migrate). You can run the following command against your SQL Azure database to create a clustered index for this table after receiving this error:
CREATE CLUSTERED INDEX [idx_schema_migrations_version] ON [schema_migrations] ([version])
After creating the clustered index, rerun the migration and it should succeed.

 

Using Ruby OData

The Ruby OData gem allows you to connect to an OData service. OData is a RESTful method of accessing data over the internet, using standards such as JSON, AtomPub, and HTTP.  For more information on OData, see http://www.odata.org/.

To configure SQL Azure for OData

OData support for SQL Azure is currently a Community Technical Preview (CTP) and can be accessed at http://www.sqlazurelabs.com.  To enable OData for an existing database, perform the following steps:
  1. Using your browser, navigate to https://www.sqlazurelabs.com/ and select the OData link. You must sign in with the login associated with your Windows Azure subscription.
  2. Enter the name of the SQL Azure server that your database resides on, along with the administrator login and password. Select Connect to continue.
  3. Select a database, and then check 'Enable OData'.
  4. Either select an account to use for anonymous access, or click Add to add a federated user.  You will finally be presented with the URL for the new OData service.

To connect to the OData service using Ruby OData

The following code will connect to an OData service that contains a database named 'testdb'.  The code will then select rows from a table named 'People', and will display the contents of the 'fname' and 'email' fields.

require 'ruby_odata'

svc=OData::Service.new "https://odata.sqlazurelabs.com/OData.svc/v0.1/servername/testdb"
svc.People
people=svc.execute
people.each {|person| puts "#{person.fname} can be contacted at #{person.email}" }

 

References

 

See Also

 

Sort by: Published Date | Most Recent | Most Useful
Comments
  • Interesting article. However in my experience, it is much much easier to use jruby and the JDBC SQL server driver.

    Just download the jdbc jar (sqljdbc4.jar), the activerecord jdbc adapter (activerecord-jdbc-adapter) and then use the following configuration in your database.yml:

    azureprod:

     adapter:  "jdbc"

     username: "username"

     password: "your_password"

     driver:   "com.microsoft.sqlserver.jdbc.SQLServerDriver"

     url:      "jdbc:sqlserver://YourDatabaseEndpoint.database.windows.net:1433;databaseName=DatabaseNameDB"

    cheers,

    thomas

Page 1 of 1 (1 items)