File: sequence.cpp

package info (click to toggle)
pgmodeler 1.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 14,276 kB
  • sloc: cpp: 99,283; xml: 27; sh: 15; makefile: 6
file content (522 lines) | stat: -rw-r--r-- 14,620 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
/*
# PostgreSQL Database Modeler (pgModeler)
#
# (c) Copyright 2006-2026 - Raphael Araújo e Silva <raphael@pgmodeler.io>
#
# DEVELOPMENT, MAINTENANCE AND COMMERCIAL DISTRIBUTION BY:
# Nullptr Labs Software e Tecnologia LTDA <contact@nullptrlabs.io>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# The complete text of GPLv3 is at LICENSE file on source code root directory.
# Also, you can get the complete GNU General Public License at <http://www.gnu.org/licenses/>
*/

#include "sequence.h"
#include "coreutilsns.h"

const QString Sequence::MaxPositiveValue {"+2147483647"};
const QString Sequence::MaxNegativeValue {"-2147483648"};
const QString Sequence::MaxSmallPositiveValue {"+32767"};
const QString Sequence::MaxSmallNegativeValue {"-32768"};
const QString Sequence::MaxBigPositiveValue {"+9223372036854775807"};
const QString Sequence::MaxBigNegativeValue {"-9223372036854775808"};

Sequence::Sequence()
{
	obj_type=ObjectType::Sequence;
	cycle=false;
	setDefaultValues(PgSqlType("serial"));
	owner_col=nullptr;

	attributes[Attributes::Increment]="";
	attributes[Attributes::MinValue]="";
	attributes[Attributes::MaxValue]="";
	attributes[Attributes::Start]="";
	attributes[Attributes::Cache]="";
	attributes[Attributes::Cycle]="";
	attributes[Attributes::OwnerColumn]="";
	attributes[Attributes::Table]="";
	attributes[Attributes::Column]="";
	attributes[Attributes::ColIsIdentity]="";
}

bool Sequence::isZeroValue(const QString &value)
{
	if(value.isEmpty())
		return false;

	unsigned i, count;
	bool is_zero;

	i=0;
	is_zero=true;
	count=value.size();

	while(i < count && is_zero)
	{
		is_zero=(value[i]=='0' || value[i]=='+' || value[i]=='-');
		i++;
	}

	return is_zero;
}

bool Sequence::isValidValue(const QString &value)
{
	if(value.isEmpty())
		return false;

	/* To be valid the value can be start with + or -, have only numbers and
		it's length must not exceed the MAX_POSITIVE_VALUE length */
	if(value.size() > MaxBigPositiveValue.size())
		return false;
	else
	{
		unsigned i, count;
		bool is_oper=false, is_num=false, is_valid=true;

		count=value.size();
		for(i=0; i < count && is_valid; i++)
		{
			if((value[i]=='-' || value[i]=='+') && !is_num)
			{
				if(!is_oper) is_oper=true;
			}
			else if((value[i]>='0' && value[i]<='9'))
			{
				if(!is_num) is_num=true;
			}
			else is_valid=false;
		}

		if(!is_num) is_valid=false;
		return is_valid;
	}
}

QString Sequence::formatValue(const QString &value)
{
	QString fmt_value;

	//Before format the value checks if it is valid
	if(isValidValue(value))
	{
		unsigned i, count, neg_cnt;

		i=neg_cnt=0;
		count=value.size();

		/* Counts the number of negative operator because
		 the quantity can interfere on the final result
		 of formating */
		while((value[i]=='+' || value[i]=='-') && i < count)
		{
			if(value[i]=='-') neg_cnt++;
			i++;
		}

		//When the negative signal count is odd the number is negative
		if(neg_cnt % 2 != 0) fmt_value+="-";

		fmt_value+=value.mid(i, count);
	}

	return fmt_value;
}

int Sequence::compareValues(QString value1, QString value2)
{
	if(value1==value2 || value1.isEmpty() || value2.isEmpty())
		return 0;
	else
	{
		char ops[2]={'\0','\0'};
		unsigned i, idx, count;
		QString *vet_values[2]={&value1, &value2}, aux_value;

		if(value1.size() < value2.size())
			value1=value1.rightJustified(value1.size() + (value2.size()-value1.size()),'0');
		else if(value1.size() > value2.size())
			value2=value2.rightJustified(value2.size() + (value1.size()-value2.size()),'0');

		for(i=0; i < 2; i++)
		{
			//Gets the value signal
			ops[i]=vet_values[i]->at(0).toLatin1();

			//Case the value doesn't has a + it will be append
			if(ops[i]!='-' && ops[i]!='+') ops[i]='+';

			idx=0;
			count=vet_values[i]->size();
			while(idx < count)
			{
				if(vet_values[i]->at(idx)!='+' &&
						vet_values[i]->at(idx)!='-')
					aux_value+=vet_values[i]->at(idx);
				else
					aux_value+='0';

				idx++;
			}
			(*vet_values[i])=aux_value;
			aux_value="";
		}

		if(ops[0]==ops[1] && value1==value2)
			return 0;
		else if((ops[0]=='-' && ops[1]=='-' && value1 > value2) ||
				(ops[0]=='+' && ops[1]=='+' && value1 < value2) ||
				(ops[0]=='-' && ops[1]=='+'))
			return -1;
		else
			return 1;
	}
}

void Sequence::setDefaultValues(PgSqlType serial_type)
{
	QString min, max;

	if(serial_type=="smallserial" ||
		 serial_type.isEquivalentTo(PgSqlType("smallint")))
	{
		min=MaxSmallNegativeValue;
		max=MaxSmallPositiveValue;
	}
	else if(serial_type=="bigserial" ||
					serial_type.isEquivalentTo(PgSqlType("bigint")))
	{
		min=MaxBigNegativeValue;
		max=MaxBigPositiveValue;
	}
	else
	{
		min=MaxNegativeValue;
		max=MaxPositiveValue;
	}

	setValues(min, max, "1", "1", "1");
}


void Sequence::setName(const QString &name)
{
	QString prev_name=this->getName(true);

	BaseObject::setName(name);
	PgSqlType::renameUserType(prev_name, this, this->getName(true));
}

void Sequence::setSchema(BaseObject *schema)
{
	PhysicalTable *table=nullptr;
	QString prev_name=this->getName(true);

	if(owner_col)
	{
		//Gets the table that owns the column
		table=dynamic_cast<PhysicalTable *>(owner_col->getParentTable());

		//Raises an error when the passed schema differs from the table schema
		if(table && table->getSchema()!=schema)
			throw Exception(ErrorCode::AsgSchemaSequenceDiffersTableSchema,__PRETTY_FUNCTION__,__FILE__,__LINE__);
	}

	BaseObject::setSchema(schema);
	PgSqlType::renameUserType(prev_name, this, this->getName(true));
}

void Sequence::setCycle(bool value)
{
	setCodeInvalidated(cycle != value);
	cycle=value;
}

void Sequence::setValues(QString minv, QString maxv, QString inc, QString start, QString cache)
{
	minv=formatValue(minv);
	maxv=formatValue(maxv);
	inc=formatValue(inc);
	start=formatValue(start);
	cache=formatValue(cache);

	if(compareValues(minv,maxv) > 0)
		throw Exception(ErrorCode::AsgInvalidSequenceMinValue,__PRETTY_FUNCTION__,__FILE__,__LINE__);
	//Raises an error when the start value is less that min value or grater than max value
	else if(compareValues(start, minv) < 0 ||	compareValues(start, maxv) > 0)
		throw Exception(ErrorCode::AsgInvalidSequenceStartValue,__PRETTY_FUNCTION__,__FILE__,__LINE__);
	//Raises an error when the increment value is null (0)
	else if(isZeroValue(inc))
		throw Exception(ErrorCode::AsgInvalidSequenceIncrementValue,__PRETTY_FUNCTION__,__FILE__,__LINE__);
	//Raises an error when the cache value is null (0)
	else if(isZeroValue(cache))
		throw Exception(ErrorCode::AsgInvalidSequenceCacheValue,__PRETTY_FUNCTION__,__FILE__,__LINE__);

	this->min_value=minv;
	this->max_value=maxv;
	this->increment=inc;
	this->cache=cache;
	this->start=start;

	setCodeInvalidated(true);
}

void Sequence::setOwnerColumn(PhysicalTable *table, const QString &col_name)
{
	if(!table || col_name.isEmpty())
		this->owner_col=nullptr;
	else if(table)
	{
		//Raises an error if the table schema differs from the sequence schema
		if(table->getSchema()!=this->schema)
			throw Exception(Exception::getErrorMessage(ErrorCode::AsgSeqOwnerTableDifferentSchema)
							.arg(this->getName(true)),
							ErrorCode::AsgSeqOwnerTableDifferentSchema,__PRETTY_FUNCTION__,__FILE__,__LINE__);

		//Raises an error when the table owner role differs from the sequence owner
		if(table->getOwner()!=this->owner)
			throw Exception(Exception::getErrorMessage(ErrorCode::AsgSeqOwnerTableDifferentRole)
							.arg(this->getName(true)),
							ErrorCode::AsgSeqOwnerTableDifferentRole,__PRETTY_FUNCTION__,__FILE__,__LINE__);

		//Gets the column with the passed name
		this->owner_col=table->getColumn(col_name);

		//Raises an error if the column doesn't exists
		if(!this->owner_col)
			throw Exception(Exception::getErrorMessage(ErrorCode::AsgInexistentSeqOwnerColumn)
							.arg(this->getName(true)),
							ErrorCode::AsgInexistentSeqOwnerColumn,__PRETTY_FUNCTION__,__FILE__,__LINE__);

		/* If the onwer column was added by relationship and the column id is greater than
		 sequence id, change the sequence id to be greater to avoid reference errors */
		if(this->owner_col && this->owner_col->isAddedByRelationship() &&
				this->owner_col->getObjectId() > this->object_id)
			this->object_id=BaseObject::getGlobalId();
	}

	setCodeInvalidated(true);
}

void Sequence::setOwnerColumn(Column *column)
{
	PhysicalTable *table=nullptr;

	if(!column)
		this->owner_col=nullptr;
	else
	{
		table=dynamic_cast<PhysicalTable *>(column->getParentTable());

		//Raises an error when the column doesn't has a parent table
		if(!table)
			throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidSeqOwnerColumn)
							.arg(this->getName(true)),
							ErrorCode::AsgInvalidSeqOwnerColumn,__PRETTY_FUNCTION__,__FILE__,__LINE__);

		//Raises an error if the table schema differs from the sequence schema
		if(table->getSchema()!=this->schema)
			throw Exception(Exception::getErrorMessage(ErrorCode::AsgSeqOwnerTableDifferentSchema)
							.arg(this->getName(true)),
							ErrorCode::AsgSeqOwnerTableDifferentSchema,__PRETTY_FUNCTION__,__FILE__,__LINE__);

		//Raises an error when the table owner role differs from the sequence owner
		if(table->getOwner()!=this->owner)
			throw Exception(Exception::getErrorMessage(ErrorCode::AsgSeqOwnerTableDifferentRole)
							.arg(this->getName(true)),
							ErrorCode::AsgSeqOwnerTableDifferentRole,__PRETTY_FUNCTION__,__FILE__,__LINE__);

		this->owner_col=column;

		/* If the onwer column was added by relationship and the column id is greater than
		 sequence id, change the sequence id to be greater to avoid reference errors */
		if(column && column->isAddedByRelationship() &&
				column->getObjectId() > this->object_id)
			this->object_id=BaseObject::getGlobalId();
	}

	setCodeInvalidated(true);
}

bool Sequence::isReferRelationshipAddedColumn()
{
	return (owner_col && owner_col->isAddedByRelationship());
}

bool Sequence::isCycle()
{
	return cycle;
}

QString Sequence::getMaxValue()
{
	return max_value;
}

QString Sequence::getMinValue()
{
	return min_value;
}

QString Sequence::getCache()
{
	return cache;
}

QString Sequence::getIncrement()
{
	return increment;
}

QString Sequence::getStart()
{
	return start;
}

Column *Sequence::getOwnerColumn()
{
	return owner_col;
}

QString Sequence::getSourceCode(SchemaParser::CodeType def_type)
{
	QString code_def=getCachedCode(def_type, false);
	if(!code_def.isEmpty()) return code_def;

	PhysicalTable *table=nullptr;

	if(owner_col)
	{
		attributes[Attributes::OwnerColumn]=owner_col->getSignature();
		table=dynamic_cast<PhysicalTable *>(owner_col->getParentTable());
	}

	attributes[Attributes::Table]=(table ? table->getName(true) : "");
	attributes[Attributes::Column]=(owner_col ? owner_col->getName(true) : "");

	attributes[Attributes::ColIsIdentity]=
			(owner_col && owner_col->getIdentityType() != IdentityType::Null ? Attributes::True : "");

	attributes[Attributes::Increment]=increment;
	attributes[Attributes::MinValue]=min_value;
	attributes[Attributes::MaxValue]=max_value;
	attributes[Attributes::Start]=start;
	attributes[Attributes::Cache]=cache;
	attributes[Attributes::Cycle]=(cycle ? Attributes::True : "");

	return BaseObject::__getSourceCode(def_type);
}

QString Sequence::getAlterCode(BaseObject *object)
{
	Sequence *seq=dynamic_cast<Sequence *>(object);

	if(!seq)
		throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__);

	try
	{
		PhysicalTable *table=nullptr;
		attribs_map attribs;

		attributes[Attributes::AlterCmds]=BaseObject::getAlterCode(object);

		if((this->owner_col && !seq->owner_col) ||
				(!this->owner_col && seq->owner_col) ||
				(this->owner_col && seq->owner_col &&
				 this->owner_col->getSignature()!=seq->owner_col->getSignature()))
		{
			if(seq->owner_col)
			{
				attribs[Attributes::OwnerColumn]=seq->owner_col->getSignature();
				table=dynamic_cast<PhysicalTable *>(seq->owner_col->getParentTable());

				if(table)
				{
					attribs[Attributes::Table]=table->getName(true);
					attribs[Attributes::Column]=seq->owner_col->getName(true);
				}
			}
			else
				attribs[Attributes::OwnerColumn]=Attributes::Unset;
		}

		if(!seq->increment.isEmpty() && this->increment!=seq->increment)
			attribs[Attributes::Increment]=seq->increment;

		if(!seq->min_value.isEmpty() && this->min_value!=seq->min_value)
			attribs[Attributes::MinValue]=seq->min_value;

		if(!seq->max_value.isEmpty() && this->max_value!=seq->max_value)
			attribs[Attributes::MaxValue]=seq->max_value;

		if(!seq->start.isEmpty() && this->start!=seq->start)
			attribs[Attributes::Start]=seq->start;

		if(!seq->cache.isEmpty() && this->cache!=seq->cache)
			attribs[Attributes::Cache]=seq->cache;

		if(this->cycle!=seq->cycle)
			attribs[Attributes::Cycle]=(seq->cycle ? Attributes::True : Attributes::Unset);

		copyAttributes(attribs);
		return BaseObject::getAlterCode(this->getSchemaName(), attributes, false, true);
	}
	catch(Exception &e)
	{
		throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e);
	}
}

void Sequence::operator = (Sequence &seq)
{
	QString prev_name=this->getName(true);

	*(dynamic_cast<BaseObject *>(this))=dynamic_cast<BaseObject &>(seq);

	this->cycle=seq.cycle;
	this->max_value=seq.max_value;
	this->min_value=seq.min_value;
	this->start=seq.start;
	this->increment=seq.increment;
	this->cache=seq.cache;
	this->owner_col=seq.owner_col;

	PgSqlType::renameUserType(prev_name, this, this->getName(true));
}

QString Sequence::getDataDictionary(bool md_format, const attribs_map &extra_attribs)
{
	try
	{
		attribs_map attribs;

		attribs.insert(extra_attribs.begin(), extra_attribs.end());
		attribs[Attributes::Name] = getSignature();
		attribs[Attributes::Cycle] = cycle ? CoreUtilsNs::DataDictCheckMark : "";
		attribs[Attributes::MinValue] = min_value;
		attribs[Attributes::MaxValue] = max_value;
		attribs[Attributes::Comment] = comment;

		schparser.ignoreEmptyAttributes(true);
		return schparser.getSourceCode(GlobalAttributes::getDictSchemaFilePath(md_format, getSchemaName()), attribs);
	}
	catch(Exception &e)
	{
		throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__, __FILE__, __LINE__, &e);
	}
}

void Sequence::updateDependencies()
{
	BaseObject::updateDependencies({ owner_col });
}