How to get metadata from query result,.?
I wanna get the datatype of each column from my query result,.
singles linked to a helpful post in his comment, but more specifically, here is how you can get the data type for a column from your table.
// $tbl is your Zend_Db_Table object
$info = $tbl->info(Zend_Db_Table_Abstract::METADATA); // get the table metadata, fetches it if it is not yet set
// get the data type for the "email_address" column
$type = $info['email_address']['DATA_TYPE']);
For each column in your table, you will have an array of data like so:
["column_name"] =>
array(14) {
["SCHEMA_NAME"]=> NULL
["TABLE_NAME"]=> string(8) "accounts"
["COLUMN_NAME"]=> string(10) "account_id"
["COLUMN_POSITION"]=> int(1)
["DATA_TYPE"]=> string(9) "mediumint"
["DEFAULT"]=> NULL
["NULLABLE"]=> bool(false)
["LENGTH"]=> NULL
["SCALE"]=> NULL
["PRECISION"]=> NULL
["UNSIGNED"]=> bool(true)
["PRIMARY"]=> bool(true)
["PRIMARY_POSITION"]=> int(1)
["IDENTITY"]=> bool(true)
}
Related
I'm trying to add a property to an existing jsonb column (column "data").
I want have my jsonb document to log like this
{
// ... existing properties
"Filed": false // new property
}
I tried
UPDATE "doc" SET "data" = jsonb_set("data"::jsonb, 'Filed', false, true)
I get this error:
[42883] ERROR: function jsonb_set(jsonb, unknown, boolean, boolean) does not exist
Hint: No function matches the given name and argument types.
You might need to add explicit type casts. Position: 46
It should be
jsonb_set("data"::jsonb, '{Filed}', 'false', TRUE)
The second parameter is an array denoting the path to the appropriate key, and 'false' is the string representation of a JSON boolean.
Better use the || operator.
UPDATE "doc" SET "data" = "data" || '{"Filed": false}';
This one is equivalent but more suitable for parameterization:
UPDATE "doc" SET "data" = "data" || jsonb_build_object('Filed', false);
Is there a way to write two insert statements if a javascript object's value is not an empty string, or one insert statement if it is an empty string in a postgreSQL query using node-postgres?
My database table "job" setup:
CREATE TABLE "job" (
"id" SERIAL PRIMARY KEY,
"company" VARCHAR (20) NOT NULL
);
For example, I would like this object to insert two rows:
{
company: 'Apple',
company_two: 'Google'
}
And I would like this object to insert one row:
{
company: 'Facebook',
company_two: ''
}
If the javascript object has a value for "company_two", I would like to add a second row to the database.
Here is what I have working to insert one row, but this doesn't take the other property into account:
pool.query('INSERT INTO "job" ("company") VALUES $1', [testObject.company]);
Check if the object has a value in the company_two property and act accordingly, for example:
const query = 'INSERT INTO "job" ("company") VALUES ($1)';
if (testObject.company_two != '') {
pool.query(`${query}, ($2)`, [ testObject.company, textObject.company_two ]);
} else {
pool.query(query, [ testObject.company ]);
}
This will insert a single row if company_two is an empty string and two rows if it is not and empty string. Of course you should adjust the if condition to match what you expect.
You can "unnest" the JSON to rows, and then use that as the source for an insert:
insert into job (company)
select t.comp
from jsonb_each_text('{
"company": "Apple",
"company_two": "Google"
}'::jsonb) t(k,comp)
where t.comp <> '';
will insert both companies.
And this will only insert one row:
insert into job (company)
select t.comp
from jsonb_each_text('{
"company": "Facebook",
"company_two": ""
}'::jsonb) t(k,comp)
where t.comp <> '';
I'm using jenssegers/laravel-mongodb package (for Laravel) and I'm trying to store float values in database so I can order them but it always stores them as string. I tried using $casts attribute and I tried direct casting like $some_value = (float)$value; but it doesn't work.
Is it possible to cast the attribute while calling orderBy function, in other words, is it possible to trick Eloquent so it orders the rows as float, not as string (I attempted to fix this with mutators but still no progress).
EDIT:
This is the mutator that I use. It works ok for "int" part, but when it's float then the rate is converted to string.
I tried converting everything to float but it didn't help
public function setRateAttribute($value)
{
if(strpos($value, ".") !== false or is_float($value)) {
$this->attributes['rate'] = (float)$value;
} else {
$this->attributes['rate'] = (int)$value;
}
}
EDIT2:
$c = new \App\Contractor();
$c->rate = "1.5";
$c->save();
This is example from php artisan tinker, it's the same in application only with additional fields.
The problem is that some entries are converted to float but some are string. I can't reproduce it always, it happens randomly.
This is example response when I loop through all entries and var_dump only rate:
string(5) "16.67"
string(5) "33.33"
string(5) "24.44"
string(5) "33.33"
string(5) "33.33"
string(5) "27.78"
string(5) "27.78"
string(4) "8.89"
string(4) "6.67"
string(5) "22.22"
string(5) "16.67"
int(0)
float(1.5)
float(1.5)
MongoDB doesn't support float directly; it has double instead, so you can use
$some_value = (double)$value;
and you need to make sure the syntax is correct.
Created a migration with a new field of jsonb type, not null and default value = []. (example of stored data: ["235", "214"]) and add a rule to model [['unique_users'], 'safe']
public function up()
{
$connection = Yii::$app->getDb();
$sql = 'ALTER TABLE offer ADD unique_users jsonb not null default \'[]\'';
$command = $connection->createCommand($sql, []);
$command->queryAll();
}
Result: Added a unique_users field with a default value [] to each row. jsonb_typeof(unique_users) returns an array type.
Created needed query for test
select jsonb_array_length(unique_users) from test where unique_users #> '"19"'::jsonb
Result from PgAdmin:
It seemed that everything was ready. But after saving a new record with Yii2, I received a query error:
ERROR: you can not get the length of a scalar
And I saw that another value was recorded in the field - ""
I was tryed to add the validation rule to Model: ['unique_users', 'default', 'value' => '[]'],.
Result:
...with the same problem of query - value is not an array. jsonb_typeof(unique_users) returns an string type.
How to insert empty array into jsonb column?
I think you're accidentally sending an empty string as the value for your unique_users field. If the value would be completely empty it should take the default DB value for the column. Please make sure the unique_users field is completely empty (null) when saving.
You can however also do this with a default value rule. This should do the trick:
['unique_users', 'default', 'value' => json_encode([])],
['unique_users', 'default', 'value' => []],
I am a data grid implemented in the Impresspages admin environment. The form has date fields. The problem is the following. Entered date is storage in Mysql (and logically returned too) like 000-00-00. I caught the public function createData($postData) from one field in the grid and the content is correct, the fields value are right. Let's see:
array(12) {
["securityToken"]=> string(32) "b9d273d7f6f17a43eacb61a008543d21"
["antispam"]=> array(2) { [0]=> string(0) "" [1]=> string(32)
"692a03a931157644de8a0986ebfa54ea" }
["active"]=> string(1) "1"
["starSign"]=> string(2) "22"
["startPeriod"]=> string(10) "2015-04-25"
["endPeriod"]=> string(10) "2015-04-25"
["prevLove"]=> string(25) "dsdsds"
["prevHealth"]=> string(25) "asasas"
["prevBiz"]=> string(27) "lklklklk"
["prevLucky"]=> string(27) "fgfgfgfg"
["languageId"]=> string(1) "2"
["createdAt"]=> string(19) "2015-04-22 14:02:37"
}
Look at the fields startPeriod and EndPeriod. In the data array they are set up to real values typed: 2015-04-22, However it is stored in the DB the weird value 0000-00-00. Any idea, please? Thanks.
Check the camelCase issue. Maybe in your database those fields are not in the same upper/lower case. This is the issue if you migrate your database between windows/unix. Make user that your config is exactly the same and you don't have any mistype.
you get 0000-00-00 on MySQL field when you provide incorrect value or you don't provide any value and the field is set as NOT NULL.
I personally never got such issue with Date field.