Create a new table on sails - mysql

my question is pretty simple but I can't find my answer over the web.
I'm on a project Sails/AngularJS and I simply would like to create a new table in mysql when a specific route is called.
It seems that it's not possible with waterline to create one afterwards.
I would be pleased if someone as a clue of how to resolve that.
Regards.

Waterline does not provide any function to create table.
Method 1:
But it provides Model.query() method which you can use to perform any kind of query you want.
//TestController.js
module.exports = {
action1:function(req,res){
var queryString='CREATE TABLE if not exists sailsusers.test (id INT NOT NULL,name VARCHAR(45) NULL,PRIMARY KEY (id))'
Test.query(queryString,function(err,a){
if(err)
return console.log(err);
console.log(a,'\n',b);
res.ok();
});
}
};
So that's how you can do that!
Method 2:(Risk of loosing data so never do in production)
in config/models.js add the following.
migrate: 'alter'
whenever you lift the server one table for each model will be created automatically.But No one suggest to do that in production.
This way is not preferred.

Related

Can we fetch a table models from MySql using Nodejs ORM2 without defining all the properties/fields?

I would like to know if we can fetch a table model from MySql from Database, without defining all the properties.
I'm using Node.js ORM2
const orm = require('orm');
db.define('users', {
// donot want to specify all the properties/fields
});
Above users table has already been created in DB, so I just want to get that model and not create/specify all the properties in it.
We can do this with other ORM's like Objection.js - but can't change my current implementation.
Thanks in advance,
Unfortunately, you must define properties/fields while you are defining your Models. There aren't any other options.

How to create table without schema in BigQuery by API?

Simply speaking I would create table with given name providing only data.
I have some JUnit's with sample data (jsons)
I have to provide schema for above files to create tables for them
I suppose that don't need provide above schemas.
Why? Because in BigQuery console I can create table from query (even such simple like: select 1, 'test') or I can upload json to create table with schema autodetection => probably could also do it programatically
I saw https://chartio.com/resources/tutorials/how-to-create-a-table-from-a-query-in-google-bigquery/#using-the-api and know that could parse jsons with data to queries and use Jobs.insert API to run them but it's over engineered and has some other disadvanteges e.g. boilerplate code.
After some research I found possibly simpler way of creating table on fly, but it doesn't work for me, code below:
Insert insert = bigquery.jobs().insert(projectId,
new Job().setConfiguration(
new JobConfiguration().setLoad(
new JobConfigurationLoad()
.setSourceFormat("NEWLINE_DELIMITED_JSON")
.setDestinationTable(
new TableReference()
.setProjectId(projectId)
.setDatasetId(dataSetId)
.setTableId(tableId)
)
.setCreateDisposition("CREATE_IF_NEEDED")
.setWriteDisposition(writeDisposition)
.setSourceUris(Collections.singletonList(sourceUri))
.setAutodetect(true)
)
));
Job myInsertJob = insert.execute();
JSON file which is used as a source data is pointed by sourceUri, looks like:
[
{
"stringField1": "value1",
"numberField2": "123456789"
}
]
Even if I used setCreateDisposition("CREATE_IF_NEEDED") I still receive error: "Not found: Table ..."
Is there any other method in API or better approach than above to exclude schema?
The code in your question is perfectly fine, and it does create table if it doesn't exist. However, it fails when you use partition id in place of table id, i.e. when destination table id is "table$20170323" which is what you used in your job. In order to write to partition, you will have to create table first.

findOne({key:value}) or findOne().where({key:value}) when querying database with waterline?

I'm using Waterline to query MySQL database by Sails. I found 2 ways to do that.
I don't know which one is better?
By the way, how to handle error for both case?
1. Model.findOne().where({key: value}).then(function(data){
console.log(data);})
2. Phase.findOne({key: value}).then(function(data){
console.log(phase);})
Either will work. In that method you catch an error as seen below.
1. Model.findOne().where({key: value}).then(function(data){
console.log(data);}).catch(function(err){/*....*/})
2. Phase.findOne({key: value}).then(function(data){
console.log(phase);}).catch(function(err){/*....*/})
Another option
Phase.findOne({key: value}).exec(function(err, data){
if(err) /* Do something with error */
console.log(phase);
})
Also, if your searching by the Primary Key then you can do
Phase.findOne(PK)
https://github.com/balderdashy/waterline-docs/blob/master/query.md#query-language

How to get the metadata of a mysql table on sailsjs

I was wondering if you can get the metadata or the entire structure of the table and columns using sailsjs or waterline's mysql module
After hours of searching, I've finally found the holy grail. Well half of the holy grail.
Anyway, I just followed the instructions given here: https://github.com/balderdashy/sails/issues/780 then created my own custom query.
Yes its very easy to get structure of MySQL table by Waterline SalsJS...
Model.query("desc table_name",function (err, models) {
if(!err)
{
//Do somethng wth your data in models variable
}
}
)
Here table_name is your table name
For me, below code was working fine...
db('users_table').query("SHOW COLUMNS FROM users_table",function (err, models) {
if (! err )
// working with data
});

CakePHP can't find table after creating a table

I create a table directly by a query. I only want to Import some data. Therefor i execute a query which is built dynamicly and i try execute this query in a Component-class. (I use a random existing model to execute this query is there a better why?)
$query= "CREATE TABLE IF NOT EXISTS testerdbs (
'Ü1' varchar(6) COLLATE utf8_swedish_ci DEFAULT NULL,
'Ü2' varchar(6) COLLATE utf8_swedish_ci DEFAULT NULL,
'Ü3' int(3) DEFAULT NULL,
'Ü4' varchar(6) COLLATE utf8_swedish_ci DEFAULT NULL,
'Ü5' date DEFAULT NULL
)"
$data = ClassRegistry::init('import_files');
$data->query($query);
This works fine.
In the same request i want to access the created table in the controller.
App::import('Model', "testerdb");
//$this->loadModel("testerdb");
$newTable = ClassRegistry::init("testerdb");
echo '<pre>', print_r($newTable->getColumnTypes()), '</pre>';
If I try to execute this in same request i always get the error:
Error: Table testerdbs for model testerdb was not found in datasource default.
If I do exactly the same request again, everything works fine...
I google about an hour and it seemed that cake cache the model. If I execute this request again cake cache again all the tables and than cake find my new table. So I hoped to load or import the created Table in the same request, but i don't work.
Is there another way to load the table? Where is my mistake?
Thanks for help!
This might be a bit stale, but I just spent the last week trying to work around the problem and maybe this will help someone.
The root problem is that the cache of table names is initialized before you created the temporary table, so the 'setSource' function returns an error that the temporary table does not exist.
The solution is to overrid the 'setSource' function for the Model that you are creating for 'testerdb' and remove the check on table existence (i.e. everything within the test:
if (method_exists($db, 'listSources'))' )
Your model definition should look something like this:
App::uses('AppModel', 'Model');
class testerdb extends AppModel {
public function setSource($tableName) {
$this->setDataSource($this->useDbConfig);
$db = ConnectionManager::getDataSource($this->useDbConfig);
$this->table = $this->useTable = $tableName;
$this->tableToModel[$this->table] = $this->alias;
$this->schema();
}
}
Many thanks to whomever posted the link below. This has worked with my CakePHP 2.0 instance.
http://web2.0goodies.com/blog/uncategorized/mysql-temporary-tables-and-cakephp-1-3/
Why would you only want to have a temporary table? I would just temporarily store whatever data you are importing in an in-memory model or data-structure.
If the table is not temporary, then just create it statically before you run your program.