Repository: kayak/pypika (python)

Issue:
Subquery in from clause missing alias when one is explicitly set
Subqueries require an alias and should also implicitly set one if needed

```
Query.from( subquery ) .select('*')
```

Pull request:
Fixes #55 issue with subqueries in from clause missing alias

Patch:
diff --git a/pypika/queries.py b/pypika/queries.py
index 13b8b81..6cda365 100644
--- a/pypika/queries.py
+++ b/pypika/queries.py
@@ -496,7 +496,10 @@ class QueryBuilder(Selectable, Term):
         if self._insert_table and not (self._selects or self._values):
             return ''
 
-        kwargs['with_namespace'] = bool(self._joins) or 1 < len(self._from)
+        has_joins = bool(self._joins)
+        has_multiple_from_clauses = 1 < len(self._from)
+        has_subquery_from_clause = 0 < len(self._from) and isinstance(self._from[0], QueryBuilder)
+        kwargs['with_namespace'] = any((has_joins, has_multiple_from_clauses, has_subquery_from_clause))
 
         if not self._select_into and self._insert_table:
             querystring = self._insert_sql(**kwargs)


Test patch:
diff --git a/pypika/tests/test_selects.py b/pypika/tests/test_selects.py
index d25a3de..2c12652 100644
--- a/pypika/tests/test_selects.py
+++ b/pypika/tests/test_selects.py
@@ -84,6 +84,14 @@ class SelectTests(unittest.TestCase):
 
         self.assertEqual('SELECT "abc"."foo","efg"."bar" FROM "abc","efg"', str(q))
 
+    def test_select__subquery(self):
+        subquery = Query.from_(self.table_abc).select("*")
+        q = Query.from_(subquery) \
+            .select(subquery.foo, subquery.bar)
+
+        self.assertEqual('SELECT "sq0"."foo","sq0"."bar" '
+                         'FROM (SELECT * FROM "abc") "sq0"', str(q))
+
     def test_select__multiple_subqueries(self):
         subquery0 = Query.from_(self.table_abc).select("foo")
         subquery1 = Query.from_(self.table_efg).select("bar")
@@ -528,11 +536,11 @@ class SubqueryTests(unittest.TestCase):
 
         query = Query.from_(subquery).select(subquery.foo, subquery.bar, subquery.fizzbuzz)
 
-        self.assertEqual('SELECT "foo","bar","fizzbuzz" '
+        self.assertEqual('SELECT "sq0"."foo","sq0"."bar","sq0"."fizzbuzz" '
                          'FROM ('
                          'SELECT "foo","bar","fizz"+"buzz" "fizzbuzz" '
                          'FROM "abc"'
-                         ')', str(query))
+                         ') "sq0"', str(query))
 
     def test_select_from_nested_query_with_join(self):
         subquery1 = Query.from_(self.table_abc).select(