I'm trying to make a Entity using typeOrm on my NestJS, and it's not working as I expected.
I have the following entity
#Entity('TableOne')
export class TableOneModel {
#PrimaryGeneratedColumn()
id: number
#PrimaryColumn()
tableTwoID: number
#PrimaryColumn()
tableThreeID: number
#CreateDateColumn()
createdAt?: Date
}
This code generate a migration that generates a table like the example below
+--------------+-------------+------+-----+----------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+----------------------+-------+
| id | int(11) | NO | | NULL | |
| tableTwoID | int(11) | NO | | NULL | |
| tableThreeID | int(11) | NO | | NULL | |
| createdAt | datetime(6) | NO | | CURRENT_TIMESTAMP(6) | |
+--------------+-------------+------+-----+----------------------+-------+
That's ok, the problem is, that I want to the table only allow one row with tableTwoID and tableThreeID, what should I use in the Entity to generated the table as I expected it to be?
Expected to not allow rows like the example below
+----+------------+--------------+----------------------------+
| id | tableTwoID | tableThreeID | createdAt |
+----+------------+--------------+----------------------------+
| 1 | 1 | 1 | 2019-10-30 19:27:43.054844 |
| 2 | 1 | 1 | 2019-10-30 19:27:43.819174 | <- should not allow the insert of this row
+----+------------+--------------+----------------------------+
Try marking the column as Unique
#Unique()
ColumnName
This is currently expected behavior from TypeORM. According to the documentation if you have multiple #PrimaryColumn() decorators you create a composite key. The combination of the composite key columns must be unique (in your above '1' + '1' + '1' = '111' vs '2' + '1' + '1' = '211'). If you are looking to make each column unique along with being a composite primary key, you should be able to do something like #PrimaryColumn({ unique: true })
Related
I have the following structure for Users_Role table:
| role_id(PK) | role_name |
| ---------------| --------------|
| 1 | Admin |
| 2 | View |
And the following structure for Users table:
| user_id (PK) | user_role_id(FK) |
| -------------| --------------------|
| 12345 | 1 |
| 22434 | 1 |
The tables are connected by user_role_id and role_id
I want to create new records in Users Table, the thing is I only have the user_role value.
Is there a way to shortcut the way to get the value of the user_role_id, or the only way to do it is a seperate query before creating new record in Users?
const userRole = "Admin";
Users.create({
user_id:"1234",
user_role_id: ???
})
I have products and providers. Each product has an uuid and each provider has a list of uuid of products that they can provide.
How do I select all the products that a given (i.e. by provider uuid) provider can offer?
Products:
+------+------+------+
| uuid | date | name |
+------+------+------+
| 0 | - | - |
| 1 | - | - |
| 2 | - | - |
+------+------+------+
Providers:
+------+----------------+
| uuid | array_products |
+------+----------------+
| 0 | [...] |
| 1 | [...] |
| 2 | [...] |
+------+----------------+
select p.name, u.product_uuid
from products p
join
(
select unnest(array_products) as product_uuid
from providers where uuid = :target_provider_uuid
) u on p.uuid = u.product_uuid;
Please note however that your data design is not efficient and much harder to work with than a normalized one.
When trying to implement Django Social, I think i missed a migration somewhere and now when I get a twitter redirect to the site I get the following error.
Exception Value: (1054, "Unknown column 'social_auth_usersocialauth.created' in 'field list'")
I can see the table has been created, and two values aren't there in the database table:
mysql> describe social_auth_usersocialauth;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| provider | varchar(32) | NO | MUL | NULL | |
| uid | varchar(255) | NO | | NULL | |
| extra_data | longtext | NO | | NULL | |
| user_id | int | NO | MUL | NULL | |
+------------+--------------+------+-----+---------+----------------+
5 rows in set (0.17 sec)
I want to run a custom migration to add the two fields that are missing from an update to the social auth migration,
class Migration(migrations.Migration):
dependencies = [
('dbdisplay', '0001_initial'),
('social_django', '0008_partial_timestamp'),
]
operations = [
migrations.AddField(
model_name='usersocialauth',
name='created',
field=models.DateTimeField(auto_now_add=True, default=mytz.now),
preserve_default=False,
),
migrations.AddField(
model_name='usersocialauth',
name='modified',
field=models.DateTimeField(auto_now=True),
),
]
But migrations don't understand the model I am referring to, because there is an error when I run the migration:
KeyError: ('social_django', 'association')
How to used AddField in a migration where the table is not in the app's namespace?
Issue is due to old version of python-social-auth (in that case social-core and social-app-django). The social_auth_usersocialauth table is missing the following fields:
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
objects = UserSocialAuthManager()
Update your requirements.txt or pip install the latest versions.
social-auth-app-django==5.0.0
social-auth-core==4.1.0
Then
pip install -r requirements.txt
And run the migrate command in django
python manage.py migrate
Afterwards check your DB table and then you will find the missing columns.
I have this model:
class TestopiaEvent(Model):
event_id = AutoField(primary_key=True)
name = CharField(max_length=255)
start_date = DateField()
end_date = DateField()
testers_required = IntegerField()
class Meta:
constraints = [
CheckConstraint(
check=Q(start_date__lte=F('end_date'), start_date__gte=datetime.now().date()),
name='correct_datetime'
)
]
And this test:
class TestopiaEventTestCase(TestCase):
def setUp(self):
self.default_values = {
'name': 'Testopia 1',
'start_date': datetime.now().date(),
'end_date': datetime.now().date() + timedelta(days=1),
'testers_required': 1
}
self.testopia_event = TestopiaEvent(**self.default_values)
def test_save_with_valid_model_check_database(self):
self.assertIsNone(self.testopia_event.save())
And it fails with this error:
django.db.utils.IntegrityError: new row for relation "webserver_testopiaevent" violates check constraint "correct_datetime"
DETAIL: Failing row contains (1, Testopia 1, 2020-07-24 00:00:00+00, 2020-07-25 00:00:00+00, 1).
I don't understand why it is failing as it should only fail if today's date is less than the start date and the start date or/and the start date is greater than the end date, which it isn't?
What have I done wrong? Thanks
Edit: Here are the postgresdb constraints:
testopia=# \d+ webserver_testopiaevent
Table
"public.webserver_testopiaevent"
Column | Type | Collation | Nullable | Default | Storage | Stats target | Description
------------------+------------------------+-----------+----------+-----------------------------------------------------------+----------+--------------+-------------
event_id | integer | | not null | nextval('webserver_testopiaevent_event_id_seq'::regclass) | plain | |
name | character varying(255) | | not null | | extended | |
start_date | date | | not null | | plain | |
end_date | date | | not null | | plain | |
testers_required | integer | | not null | | plain | |
Indexes:
"webserver_testopiaevent_pkey" PRIMARY KEY, btree (event_id)
Check constraints:
"correct_datetime" CHECK (start_date >= statement_timestamp() AND start_date <= end_date)
Access method: heap
Now() returns a DateTimeField() so with the timestamp addition it will be more than the current date if my DateField is set to the same date.
The table i developed is below one
create table userevent(id uuid,eventtype text,sourceip text,user text,sessionid text,roleid int,menu text,action text,log text,date timestamp,PRIMARY KEY (id,eventtype,user));
id | eventtype | user | action | date | log | menu | roleid | sessionid | sourceip
--------------------------------------+-----------+---------+--------+--------------------------+----------+-----------+--------+-----------+--------------
b15c6780-d69e-11e8-bb9a-59dfa00365c6 | DemoType | Aqib | Login | 2018-10-01 04:05:00+0000 | demolog | demomenu | 1 | Demo_1 | 121.11.11.12
95df3410-d69e-11e8-bb9a-59dfa00365c6 | DemoType | Aqib | Login | 2018-09-30 22:35:00+0000 | demolog | demomenu | 1 | Demo_1 | 121.11.11.12
575b05c0-d69e-11e8-bb9a-59dfa00365c6 | DemoType | Aqib | Login | 2018-10-01 04:05:00+0000 | demolog | demomenu | 1 | Demo_1 | 121.11.11.12
e6cbc190-d69e-11e8-bb9a-59dfa00365c6 | DemoType3 | Jasim | Login | 2018-05-31 22:35:00+0000 | demolog3 | demomenu3 | 3 | Demo_3 | 121.11.11.12
d66992a0-d69e-11e8-bb9a-59dfa00365c6 | DemoType | Shafeer | Login | 2018-07-31 22:35:00+0000 | demolog | demomenu | 2 | Demo_2 | 121.11.11.12
But when i queried as below,
select * from userevent where user='Aqib';
Its showing some thing like this : InvalidRequest: Error from server: code=2200 [Invalid query] message="PRIMARY KEY column "user" cannot be restricted as preceding column "eventtype" is not restricted"
What is the error...........
You need to read about data modelling for Cassandra, or for example take DS220 course on the DataStax Academy. Every row has primary key consisting of the partition key that defines on which node the data is located, and clustering keys that define placement inside partition. In your case, your primary key consists at least from id, eventtype, user. To put condition on user you need to specify both id and eventtype.
You can add the index, or materialized view to access only by user, but I recommend to get more into data modelling first - define your queries, and then build table structures about queries that you need to perform.