3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rubyでSQLを書き換える

Posted at

インストール

rubyとsql-parserをセットアップする
[vagrant@localhost ~]$ sudo yum install ruby-devel
[vagrant@localhost ~]$ sudo gem install sql-parser
[vagrant@localhost ~]$ irb

サンプルコード

SQLのfromを書き換える
irb(main):001:0> require 'sql-parser'
irb(main):002:0> parser = SQLParser::Parser.new
irb(main):003:0> ast = parser.scan_str('SELECT * FROM users WHERE id = 1')
irb(main):004:0> users = SQLParser::Statement::Table.new('users_001')
irb(main):005:0> from_clause = SQLParser::Statement::FromClause.new(users)
irb(main):006:0> where_clause = ast.query_expression.table_expression.where_clause
irb(main):007:0> table_expression = SQLParser::Statement::TableExpression.new(from_clause, where_clause)
irb(main):008:0> list = ast.query_expression.list
irb(main):009:0> select_statement = SQLParser::Statement::Select.new(list, table_expression)
irb(main):010:0> select_statement.to_sql
=> "SELECT * FROM `users_001` WHERE `id` = 1"

ライブラリ

参考

以上

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?