开发者

How can I generate sql inserts from pipe delimited data?

开发者 https://www.devze.com 2023-02-03 20:10 出处:网络
I\'ve got a small project that I would like to attempt to do in Haskell. Given a set of delimited data in t开发者_运维技巧he following format:

I've got a small project that I would like to attempt to do in Haskell. Given a set of delimited data in t开发者_运维技巧he following format:

1|Star Wars: Episode IV - A New Hope|1977|Action,Sci-Fi|George Lucas 2|Titanic|1997|Drama,History,Romance|James Cameron

In Haskell, how can I generate sql insert statements in this format?

insert into table values(1,"Star Wars: Episode IV - A New Hope",1977","Action,Sci-Fi","George Lucas",0); insert into table values(2,"Titanic",1997,"Drama,History,Romance","James Cameron",0);

To simplify the problem, let's allow for a parameter to tell which columns are text or numeric. (e.g. 0,1,0,1,1)

Here's a solution in Perl. Now I'd like to add Haskell to my toolkit.

my @ctypes=qw/0 1 0 1 1/;

while(<>) {
  chop;
  @F=split('\|', $_);
  print "insert into table values(";
  foreach my $col (@F) {
    my $type=shift(@ctypes);
    print ($type == 1 ? '"'.$col.'"' : $col);
    print ",";
  }

  print "0);\n";
}


import Control.Arrow
import Data.List

main :: IO ()
main = interact $ unlines . map (makeInsert . splitOn '|') . lines

splitOn :: (Eq a) => a -> [a] -> [[a]]
splitOn delim = unfoldr (fmap break') . return
  where break' = second (stripPrefix [delim]) . break (== delim)

makeInsert :: [String] -> String
makeInsert parts = "insert into table values(" ++ intercalate "," values ++ ");"
  where values = zipWith ($) [id, show, id, show, show] parts ++ ["0"]

although you might want to use Data.List.Split.splitOn instead of writing your own, and show isn't necessarily the right way to quote strings.


Read in the data, split at the pipe symbols, escape all your values correctly, and use string concatenation to build up your query.

0

精彩评论

暂无评论...
验证码 换一张
取 消