Using m4 to Quickly Produce SQL

Published on January 5, 2010 by Andrew Sledge in Quick Tips

Using m4 to produce SQL is quick and easy.  m4 is a macro processing language and is available on all *nix platforms. Copy the following, save it to a file called test.m4 and run it as:

$ m4 test.m4 < insertusers.sql

and now in the file test.m4:

divert(-1)  
changequote(`[', `]')  
define([foreach], [pushdef([$1], [])_foreach([$1], [$2], [$3])popdef([$1])]) 
define([_arg1], [$1])  
define([_foreach], 	[ifelse([$2], [()], , 		
[ 	define([$1], _arg1$2)$3[]_foreach([$1], (shift$2), [$3])])])  
# traceon([define], [foreach], [_foreach], [ifelse])  
divert  
# change this number to the starting number of your user ids  
define([UID],[1])    
foreach([USEREMAIL], 	
  [(user1, user2, user3, user4, user5, user6)], 	 
  [INSERT INTO users (uid, name, mail) VALUES ('UID','USEREMAIL','USEREMAIL@example.com'); 	 
  INSERT INTO roles (uid, role) VALUES ('UID','somerole');dnl 	 
define([UID], eval(UID + 1)) ])

Especially handy for mass producing Drupal accounts on the fly.

Tags: m4 sql     Permalink   Bookmark and Share

Comments


No comments for this post.

Post a comment