1#! /usr/local/bin/perl -ws 2 3use Parse::RecDescent; 4 5 6my $grammar = <<'EOGRAMMAR'; 7 8translate: select 9 | sum 10 | identify 11 | { "Could you rephase that?\n" } 12 13select: ask_select qualifier(?) field /of/ qualifier(?) table 14 { "SELECT DISTINCT $item[3]\nFROM $item[6]\n" } 15 | ask_select qualifier(?) table /'?/ qualifier(?) field 16 { "SELECT DISTINCT $item[6]\nFROM $item[3]\n" } 17 | ask_select qualifier(?) table 18 { "SELECT *\nFROM $item[3]\n" } 19 20sum: ask_count table prep qualifier field prep(?) value 21 { "SELECT COUNT(*)\nFROM $item[2]\n" . 22 "WHERE $item[5] = $item[7]\n" } 23 | ask_count table 24 { "SELECT COUNT(*)\nFROM $item[2]\n" } 25 26identify: ask_select(?) /who supplies/ qualifier value 27 { "SELECT supplier\nFROM merchandise\n" . 28 "WHERE name = $item[4]\n" } 29 30 | whats qualifier field /of/ qualifier /suppliers? of/ value 31 { "SELECT suppliers.$item[3]\n" . 32 "FROM suppliers, products\n" . 33 "WHERE products.name = $item[-1]\n" . 34 "AND suppliers.name = products.supplier \n" } 35 36 37 38 39field: /(name)s?/ { $1 } 40 | /(product)s?/ { $1 } 41 | /(id)(entit(y|ies))?/ { $1 } 42 | /(quantit(y|ies))/ { $1 } 43 | /(received)s?/ { $1 } 44 | /(supplier)s?/ { $1 } 45 | /(cost)s?/ { $1 } 46 | /(address)(es)?/ { $1 } 47 48table: /suppliers?/ { 'suppliers' } 49 | 'merchandise' 50 | /orders?/ { 'orders' } 51 52qualifier: /the|every|all( the)?|any|our/ 53 54ask_select: reply to_me 55 56ask_count: ask_select(?) /how (many|much)/ 57 58reply: /tell|show|list/ 59 60value: /\w+/ { qq{'$item[1]'} } 61 62to_me: /((to )?(me|us))?/ 63 64whats: /what's|what (is|are)/ 65 66prep: /for|of|with|by/ 67 68EOGRAMMAR 69 70my $parser = Parse::RecDescent->new($grammar) 71 or die "Bad grammar"; 72 73$| = 1; 74while (<DATA>) 75{ 76 print "> "; 77 sleep 1; 78 print; <>; 79 my $SQL = $parser->translate($_); 80 print $SQL, "\n"; 81} 82 83__DATA__ 84how many orders for the product spam are there? 85tell me how many suppliers by the name of Jones we have 86what are the names of our suppliers of trinitrotoluene? 87tell me our suppliers' names 88list our merchandise 89show us the suppliers of the mechanise 90list all supplier names 91how many orders are there? 92how much merchandise do we carry? 93who supplies our nitrocelluose? 94tell me who supplies our ethylacetate? 95what are the addresses of our suppliers of trinitrotoluene? 96