Search code examples
javascriptsqlcsvalasql

AlaSQL inserting into table from CSV doesn't work


Trying to copy CSV data to internal table of AlaSQL. But SELECT * INTO tab FROM CSV() - simply doesn't work. Nothing changed after this. Table tab still empty, but direct select works fine. What i'm doing wrong?

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
  <div id="res1"></div>
  <div id="res2"></div>
	<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/alasql/0.3.3/alasql.min.js"></script>
  
	<script type="text/sql" id='sql'>
		CREATE table tab(c1 integer);
		
		select count(*) as c1
		INTO tab 
		from CSV("https://rawgit.com/thephpleague/csv/master/examples/data/prenoms.csv");
		-- tab still empty!
		
		select *
		into HTML("#res1",{headers:true})
		from tab;

		--direct select works
		select count(*) as c1
		into HTML("#res2",{headers:true})
		from CSV("https://rawgit.com/thephpleague/csv/master/examples/data/prenoms.csv");

	</script>
	<script type="text/javascript">
		alasql('SOURCE "#sql"')
	</script>

</body>
</html>


Solution

  • Interacting with a file will make the request async. At the moment the lib cant figure out how to wait for the response of an async statement in a multi-statement command.

    To solve his you can use a promise notation for each async chuck of the total statement:

    <script type="text/sql" id='sql'>
        CREATE table tab(c1 integer);
    
        select count(*) as c1
        INTO tab 
        from CSV("https://rawgit.com/thephpleague/csv/master/examples/data/prenoms.csv");
        -- tab still empty!
    </script>
    <script type="text/sql" id='sql2'>
        select *
        into HTML("#res1",{headers:true})
        from tab;
    
        --direct select works
        select count(*) as c1
        into HTML("#res2",{headers:true})
        from CSV("https://rawgit.com/thephpleague/csv/master/examples/data/prenoms.csv");
    
    </script>
    <script type="text/javascript">
        alasql.promise(['SOURCE "#sql"','SOURCE "#sql2"'])
    </script>